My Learning Notes node----Node.js+socket.io Live Chat (2)

Source: Internet
Author: User
Tags emit live chat hasownproperty

Don't say much nonsense, just stick to the code. The comments are very detailed.

Service-Side code:

/**
* Created by LZX on 2015/10/7.
*/
(function () {
var d = document,
w = window,
p = parseint,
DD = d.documentelement,
db = D.body,
DC = D.compatmode = = ' Css1compat ',
DX = DC? Dd:db,
EC = encodeURIComponent;


Window. CHAT = {
MsgObj:document.getElementById ("message"),
Screenheight:window.innerHeight? Window.innerHeight:dx.clientHeight,
Username:null,
Userid:null,
Socket:null,
Keep the browser scroll bar at the lowest part
Scrolltobottom:function () {
Window.scrollto (0, this.msgObj.clientHeight);
},
Exit, this example is just a simple refresh
Logout:function () {
Location.reload ();
},
Submit Chat Message Content
Submit:function () {
var content = document.getElementById ("content"). Value;
if (content! = ") {
var obj = {
Userid:this.userid,
Username:this.username,
Content:content
};
This.socket.emit (' message ', obj);
document.getElementById ("Content"). Value = ';
}
return false;
},
Genuid:function () {
return new Date (). GetTime () + "" +math.floor (Math.random () *899+100);
},
Update system messages, in this case, when the user joins, exits, calls
Updatesysmsg:function (O, action) {
Current Online user list
var onlineusers = o.onlineusers;
Current number of people online
var onlinecount = O.onlinecount;
New user-joined information
var user = O.user;

Update online numbers
var userhtml = ';
var separator = ';
For (key in Onlineusers) {
if (Onlineusers.hasownproperty (key)) {
Userhtml + = Separator+onlineusers[key];
Separator = ', ';
}
}
document.getElementById ("Onlinecount"). InnerHTML = ' current total of ' +onlinecount+ ' people online, online list: ' +userhtml;

adding system messages
var html = ';
HTML + = ' <div class= "Msg-system" > ";
HTML + = User.username;
HTML + = (action = = ' login ')? ' joined the chat room ': ' exited the chat room ';
HTML + = ' </div> ';
var section = document.createelement (' section ');
Section.classname = ' System J-mjrlinkwrap j-cutmsg ';
section.innerhtml = html;
This.msgObj.appendChild (section);
This.scrolltobottom ();
},
First interface user submits user name
Usernamesubmit:function () {
var username = document.getElementById ("username"). Value;
if (username! = "") {
d.getElementById ("username"). Value = ';
d.getElementById ("Loginbox"). Style.display = ' None '; Hide the name input box
d.getElementById ("Chatbox"). Style.display = ' block ';//Display the Chat interface
This.init (username); Calling the Init method
}
return false;
},
Init:function (username) {
/*
The client generates the UID based on time and random numbers, which allows the chat room user name to be duplicated.
*/
This.userid = This.genuid ();
This.userid=username;
This.username = Username;

document.getElementById ("Showusername"). InnerHTML = This.username;
This.msgObj.style.minHeight = (this.screenheight-document.body.clientheight + this.msgObj.clientHeight) + "px";
This.scrolltobottom ();

Connecting WebSocket back-end servers
This.socket = Io.connect (' ws://localhost:3000 ');

Tell the server that a user is logged on
This.socket.emit (' login ', {userid:this.userid, username:this.username});

Listen for new user login
This.socket.on (' Login ', function (o) {
Chat.updatesysmsg (o, ' login ');
});

Listener user exits
This.socket.on (' Logout ', function (o) {
Chat.updatesysmsg (o, ' logout ');
});

Listening for message sending
This.socket.on (' message ', function (obj) {
var isme = (Obj.userid = = Chat.userid)? True:false;
var contentdiv = ' <div> ' +obj.content+ ' </div> ';
var usernamediv = ' <span> ' +obj.username+ ' </span> ';

var section = document.createelement (' section ');
if (isme) {
Section.classname = ' user ';
section.innerhtml = Contentdiv + usernamediv;
} else {
section.classname = ' service ';
section.innerhtml = Usernamediv + contentdiv;
}
CHAT.msgObj.appendChild (section);
Chat.scrolltobottom ();
});

}
};
Submit a user name by "enter"
document.getElementById ("username"). onkeydown = function (e) {
E = e | | Event
if (E.keycode = = = 13) {
Chat.usernamesubmit ();
}
};
Submit information by "enter"
document.getElementById ("Content"). onkeydown = function (e) {
E = e | | Event
if (E.keycode = = = 13) {
Chat.submit ();
}
};
})();

The interface HTML code is not released here.
Client main code:

/**
* Created by LZX on 2015/10/7.
*/
(function () {
var d = document,
w = window,
p = parseint,
DD = d.documentelement,
db = D.body,
DC = D.compatmode = = ' Css1compat ',
DX = DC? Dd:db,
EC = encodeURIComponent;


Window. CHAT = {
MsgObj:document.getElementById ("message"),
Screenheight:window.innerHeight? Window.innerHeight:dx.clientHeight,
Username:null,
Userid:null,
Socket:null,
Keep the browser scroll bar at the lowest part
Scrolltobottom:function () {
Window.scrollto (0, this.msgObj.clientHeight);
},
Exit, this example is just a simple refresh
Logout:function () {
Location.reload ();
},
Submit Chat Message Content
Submit:function () {
var content = document.getElementById ("content"). Value;
if (content! = ") {
var obj = {
Userid:this.userid,
Username:this.username,
Content:content
};
This.socket.emit (' message ', obj);
document.getElementById ("Content"). Value = ';
}
return false;
},
Genuid:function () {
return new Date (). GetTime () + "" +math.floor (Math.random () *899+100);
},
Update system messages, in this case, when the user joins, exits, calls
Updatesysmsg:function (O, action) {
Current Online user list
var onlineusers = o.onlineusers;
Current number of people online
var onlinecount = O.onlinecount;
New user-joined information
var user = O.user;

Update online numbers
var userhtml = ';
var separator = ';
For (key in Onlineusers) {
if (Onlineusers.hasownproperty (key)) {
Userhtml + = Separator+onlineusers[key];
Separator = ', ';
}
}
document.getElementById ("Onlinecount"). InnerHTML = ' current total of ' +onlinecount+ ' people online, online list: ' +userhtml;

adding system messages
var html = ';
HTML + = ' <div class= "Msg-system" > ";
HTML + = User.username;
HTML + = (action = = ' login ')? ' joined the chat room ': ' exited the chat room ';
HTML + = ' </div> ';
var section = document.createelement (' section ');
Section.classname = ' System J-mjrlinkwrap j-cutmsg ';
section.innerhtml = html;
This.msgObj.appendChild (section);
This.scrolltobottom ();
},
First interface user submits user name
Usernamesubmit:function () {
var username = document.getElementById ("username"). Value;
if (username! = "") {
d.getElementById ("username"). Value = ';
d.getElementById ("Loginbox"). Style.display = ' None '; Hide the name input box
d.getElementById ("Chatbox"). Style.display = ' block ';//Display the Chat interface
This.init (username); Calling the Init method
}
return false;
},
Init:function (username) {
/*
The client generates the UID based on time and random numbers, which allows the chat room user name to be duplicated.
*/
This.userid = This.genuid ();
This.userid=username;
This.username = Username;

document.getElementById ("Showusername"). InnerHTML = This.username;
This.msgObj.style.minHeight = (this.screenheight-document.body.clientheight + this.msgObj.clientHeight) + "px";
This.scrolltobottom ();

Connecting WebSocket back-end servers
This.socket = Io.connect (' ws://localhost:3000 ');

Tell the server that a user is logged on
This.socket.emit (' login ', {userid:this.userid, username:this.username});

Listen for new user login
This.socket.on (' Login ', function (o) {
Chat.updatesysmsg (o, ' login ');
});

Listener user exits
This.socket.on (' Logout ', function (o) {
Chat.updatesysmsg (o, ' logout ');
});

Listening for message sending
This.socket.on (' message ', function (obj) {
var isme = (Obj.userid = = Chat.userid)? True:false;
var contentdiv = ' <div> ' +obj.content+ ' </div> ';
var usernamediv = ' <span> ' +obj.username+ ' </span> ';

var section = document.createelement (' section ');
if (isme) {
Section.classname = ' user ';
section.innerhtml = Contentdiv + usernamediv;
} else {
section.classname = ' service ';
section.innerhtml = Usernamediv + contentdiv;
}
CHAT.msgObj.appendChild (section);
Chat.scrolltobottom ();
});

}
};
Submit a user name by "enter"
document.getElementById ("username"). onkeydown = function (e) {
E = e | | Event
if (E.keycode = = = 13) {
Chat.usernamesubmit ();
}
};
Submit information by "enter"
document.getElementById ("Content"). onkeydown = function (e) {
E = e | | Event
if (E.keycode = = = 13) {
Chat.submit ();
}
};
})();



Recently posted two runs, after all, no picture no truth:
Run first, the server will be prompted to listen on Port 3000.


Open Http://www.localhost:3000/



Enter the name to enter the chat interface

Then open a http://www.localhost:3000/to simulate multiple clients

Start chatting, small A, small B interface respectively




At the same time, the server will also have a corresponding prompt message

Finally thank http://www.plhwin.com/2014/05/28/nodejs-socketio/, this project is also looking at the predecessor of the build out (plagiarism is just for faster digestion, get started), can digest very good. But there is time I will improve, send pictures, expressions, documents and other functions follow-up will be perfect.
This series is always updated.





My Learning Notes node----Node.js+socket.io Live Chat (2)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.