我的学习笔记之node----node.js+socket.io实时聊天(2)

时间:2023-03-10 01:59:35
我的学习笔记之node----node.js+socket.io实时聊天(2)

废话不多说,直接贴代码吧。注释很详细了。

服务端代码:

/**
* 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,
//让浏览器滚动条保持在最低部
scrollToBottom:function(){
window.scrollTo(0, this.msgObj.clientHeight);
},
//退出,本例只是一个简单的刷新
logout:function(){
location.reload();
},
//提交聊天消息内容
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);
},
//更新系统消息,本例中在用户加入、退出的时候调用
updateSysMsg:function(o, action){
//当前在线用户列表
var onlineUsers = o.onlineUsers;
//当前在线人数
var onlineCount = o.onlineCount;
//新加入用户的信息
var user = o.user; //更新在线人数
var userhtml = '';
var separator = '';
for(key in onlineUsers) {
if(onlineUsers.hasOwnProperty(key)){
userhtml += separator+onlineUsers[key];
separator = '、';
}
}
document.getElementById("onlinecount").innerHTML = '当前共有 '+onlineCount+' 人在线,在线列表:'+userhtml; //添加系统消息
var html = '';
html += '<div class="msg-system">';
html += user.username;
html += (action == 'login') ? ' 加入了聊天室' : ' 退出了聊天室';
html += '</div>';
var section = document.createElement('section');
section.className = 'system J-mjrlinkWrap J-cutMsg';
section.innerHTML = html;
this.msgObj.appendChild(section);
this.scrollToBottom();
},
//第一个界面用户提交用户名
usernameSubmit:function(){
var username = document.getElementById("username").value;
if(username != ""){
d.getElementById("username").value = '';
d.getElementById("loginbox").style.display = 'none'; //隐藏掉名字输入框
d.getElementById("chatbox").style.display = 'block';//显示出聊天界面
this.init(username); //调用init方法
}
return false;
},
init:function(username){
/*
客户端根据时间和随机数生成uid,这样使得聊天室用户名称可以重复。
*/
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(); //连接websocket后端服务器
this.socket = io.connect('ws://localhost:3000'); //告诉服务器端有用户登录
this.socket.emit('login', {userid:this.userid, username:this.username}); //监听新用户登录
this.socket.on('login', function(o){
CHAT.updateSysMsg(o, 'login');
}); //监听用户退出
this.socket.on('logout', function(o){
CHAT.updateSysMsg(o, 'logout');
}); //监听消息发送
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();
}); }
};
//通过“回车”提交用户名
document.getElementById("username").onkeydown = function(e) {
e = e || event;
if (e.keyCode === 13) {
CHAT.usernameSubmit();
}
};
//通过“回车”提交信息
document.getElementById("content").onkeydown = function(e) {
e = e || event;
if (e.keyCode === 13) {
CHAT.submit();
}
};
})();
界面html代码这里就不放出来了。
客户端主要代码:
/**
* 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,
//让浏览器滚动条保持在最低部
scrollToBottom:function(){
window.scrollTo(0, this.msgObj.clientHeight);
},
//退出,本例只是一个简单的刷新
logout:function(){
location.reload();
},
//提交聊天消息内容
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);
},
//更新系统消息,本例中在用户加入、退出的时候调用
updateSysMsg:function(o, action){
//当前在线用户列表
var onlineUsers = o.onlineUsers;
//当前在线人数
var onlineCount = o.onlineCount;
//新加入用户的信息
var user = o.user; //更新在线人数
var userhtml = '';
var separator = '';
for(key in onlineUsers) {
if(onlineUsers.hasOwnProperty(key)){
userhtml += separator+onlineUsers[key];
separator = '、';
}
}
document.getElementById("onlinecount").innerHTML = '当前共有 '+onlineCount+' 人在线,在线列表:'+userhtml; //添加系统消息
var html = '';
html += '<div class="msg-system">';
html += user.username;
html += (action == 'login') ? ' 加入了聊天室' : ' 退出了聊天室';
html += '</div>';
var section = document.createElement('section');
section.className = 'system J-mjrlinkWrap J-cutMsg';
section.innerHTML = html;
this.msgObj.appendChild(section);
this.scrollToBottom();
},
//第一个界面用户提交用户名
usernameSubmit:function(){
var username = document.getElementById("username").value;
if(username != ""){
d.getElementById("username").value = '';
d.getElementById("loginbox").style.display = 'none'; //隐藏掉名字输入框
d.getElementById("chatbox").style.display = 'block';//显示出聊天界面
this.init(username); //调用init方法
}
return false;
},
init:function(username){
/*
客户端根据时间和随机数生成uid,这样使得聊天室用户名称可以重复。
*/
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(); //连接websocket后端服务器
this.socket = io.connect('ws://localhost:3000'); //告诉服务器端有用户登录
this.socket.emit('login', {userid:this.userid, username:this.username}); //监听新用户登录
this.socket.on('login', function(o){
CHAT.updateSysMsg(o, 'login');
}); //监听用户退出
this.socket.on('logout', function(o){
CHAT.updateSysMsg(o, 'logout');
}); //监听消息发送
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();
}); }
};
//通过“回车”提交用户名
document.getElementById("username").onkeydown = function(e) {
e = e || event;
if (e.keyCode === 13) {
CHAT.usernameSubmit();
}
};
//通过“回车”提交信息
document.getElementById("content").onkeydown = function(e) {
e = e || event;
if (e.keyCode === 13) {
CHAT.submit();
}
};
})();

最近贴两张运行效果图,毕竟没图没真相:
先运行起来,服务端会提示监听3000端口

我的学习笔记之node----node.js+socket.io实时聊天(2)

打开http://www.localhost:3000/

我的学习笔记之node----node.js+socket.io实时聊天(2)


我的学习笔记之node----node.js+socket.io实时聊天(2)

输入名字进入聊天界面

我的学习笔记之node----node.js+socket.io实时聊天(2)

我的学习笔记之node----node.js+socket.io实时聊天(2)

再打开一个http://www.localhost:3000/模拟多个客户端

我的学习笔记之node----node.js+socket.io实时聊天(2)


我的学习笔记之node----node.js+socket.io实时聊天(2)

开始聊天,小a、小b界面分别

我的学习笔记之node----node.js+socket.io实时聊天(2)

我的学习笔记之node----node.js+socket.io实时聊天(2)


我的学习笔记之node----node.js+socket.io实时聊天(2)


我的学习笔记之node----node.js+socket.io实时聊天(2)


同时服务端也会有相应的提示消息

我的学习笔记之node----node.js+socket.io实时聊天(2)


我的学习笔记之node----node.js+socket.io实时聊天(2)


最后感谢http://www.plhwin.com/2014/05/28/nodejs-socketio/,这个项目也是看着前辈的搭出来的(抄袭仅仅是为了更快的消化,上手),能消化很不错了。不过有时间我会改进的,发送图片,表情,文件等功能后续都会完善。
此系列会一直更新。