nodejs加WebSocket,聊天工具
2017-01-12 12:59
239 查看
1、WebSocket必须要与服务器连接,所以这里采用node起服务,这里用到了ws,,也有人用nodejs-websocket
2、首先
3、新建一个server.js 文件,用来起服务,代码如下
4、新建一个client1.html, 客户端,注意文件中引入了jquery,自己改一下文件路径吧
5、再新建一个client2.html文件, 客户端,注意文件中引入了jquery,自己改一下文件路径吧
6、先执行node server,服务跑起来,(注意:服务不跑起来,是无法聊天的)
运行:client1.html和client2.html
7、开始聊天
2、首先
npm install ws
3、新建一个server.js 文件,用来起服务,代码如下
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({ port: 8181 });
//var client1 = null,client2=null,client1Ready = false, client2Ready = false;
var config = {
client1:{
Ready:false,
pipe:null
},
client2:{
Ready:false,
pipe:null
},
client3:{
Ready:false,
pipe:null
},
client4:{
Ready:false,
pipe:null
},
}
wss.on('connection', function (ws) {
console.log('client connected');
ws.on('message', function (message) {
if(config[message]){
config[message]["Ready"] = true;
config[message]["pipe"] = ws;
}else{
var data = JSON.parse(message);
if(config[data.send]["Ready"] && config[data.receive]["Ready"] ){
ws.send(message);
config[data.receive]["pipe"].send(message);
}else{
ws.send(JSON.stringify({"error":true}));
}
}
});
ws.on("close",function(code, reason){
for(var i in config){
if(config[i].pipe === ws){
config[i].Ready = false;
config[i].pipe = null;
break;
}
}
console.log("关闭链接");
});
});
//npm install ws
4、新建一个client1.html, 客户端,注意文件中引入了jquery,自己改一下文件路径吧
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>女汉子</title> <style type="text/css"> *{ padding: 0; margin: 0; font-family: "微软雅黑"; } #chat{ width: 600px; height: 400px; margin: 50px auto; border: 4px solid yellowgreen; } p{ font-size: 16px; color: #9ACD32; padding: 0 20px; } #chat p.send{ text-align: left; color: deeppink; } #chat p.receive{ text-align: right; } .btn{ text-align: center; } .showState{ text-align: center; } .showInfo{ text-align: center; } </style> </head> <body> <div class="showState">正在链接..</div> <div class="showInfo"></div> <div id="chat"> </div> <div class="btn"> <input type="text" name="message" id="message" value="" /> <button onclick="sendMessage()">发送</button> </div> </body> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> var config = { "send":"client1", "receive":"client2", "sendNike":"女汉纸", "receiveNike":"屌丝青年" } var mes = document.getElementById("message"); var box = $("#chat"); var chatWith = $(".showInfo"); var showState = $(".showState"); var ws = new WebSocket("ws://localhost:8181"); ws.onopen = function (e) { ws.send(config.send); showState.html("链接成功!"); chatWith.html("你正在和:"+ config.receiveNike + "聊天"); } function sendMessage() { var mesage = { "send":config.send, "receive":config.receive, "message":mes.value, "sendNike":config.sendNike, }; var str = JSON.stringify(mesage); ws.send(str); } ws.onmessage=function (e) { create(JSON.parse(e.data)); }; function create(data){ if(data.error){ alert("发送失败,对方不在线!"); }else{ if(data.send == config.send ){ box.append("<p class='send'>"+ config.sendNike+":" +data.message +"</p>"); }else{ box.append("<p class='receive'>"+ data.sendNike+":" + data.message +"</p>"); } } } </script> </html>
5、再新建一个client2.html文件, 客户端,注意文件中引入了jquery,自己改一下文件路径吧
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>屌丝青年</title> <style type="text/css"> *{ padding: 0; margin: 0; font-family: "微软雅黑"; } #chat{ width: 600px; height: 400px; margin: 50px auto; border: 4px solid yellowgreen; } p{ font-size: 16px; color: #9ACD32; padding: 0 20px; } #chat p.send{ text-align: left; color: deeppink; } #chat p.receive{ text-align: right; } .btn{ text-align: center; } .showState{ text-align: center; } .showInfo{ text-align: center; } </style> </head> <body> <div class="showState">正在链接..</div> <div class="showInfo"></div> <div id="chat"> </div> <div class="btn"> <input type="text" name="message" id="message" value="" /> <button onclick="sendMessage()">发送</button> </div> </body> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> var config = { "send":"client2", "receive":"client1", "sendNike":"屌丝青年", "receiveNike":"女汉纸" } var mes = document.getElementById("message"); var box = $("#chat"); var chatWith = $(".showInfo"); var showState = $(".showState"); var ws = new WebSocket("ws://localhost:8181"); ws.onopen = function (e) { ws.send(config.send); showState.html("链接成功!"); chatWith.html("你正在和:"+ config.receiveNike + "聊天"); } function sendMessage() { var mesage = { "send":config.send, "receive":config.receive, "message":mes.value, "sendNike":config.sendNike, }; var str = JSON.stringify(mesage); ws.send(str); } ws.onmessage=function (e) { create(JSON.parse(e.data)); }; function create(data){ if(data.error){ alert("发送失败,对方不在线!"); }else{ if(data.send == config.send ){ box.append("<p class='send'>"+ config.sendNike+":" +data.message +"</p>"); }else{ box.append("<p class='receive'>"+ data.sendNike+":" + data.message +"</p>"); } } } </script> </html>
6、先执行node server,服务跑起来,(注意:服务不跑起来,是无法聊天的)
运行:client1.html和client2.html
7、开始聊天
相关文章推荐
- NodeJS、NPM安装配置步骤(windows版本)
- (5)Kurento之系统搭建III-运行环境/工具
- Dom4j中SelectNodes使用方法
- Node.js制作简单聊天室
- node.js.使用sudo安装的时候遇到的问题!
- Node.js学习笔记(一):快速开始
- XML DOM nodeType 属性值代表的意思
- NodeJs调用系统命令测试电脑IO性能
- SecondaryNameNode启动异常端口被占用
- hadoop2.X如何将namenode与SecondaryNameNode分开配置
- 基于node.js构建微服务中的mock服务
- Secondary Namenode - What it really do?
- Zipkin-1.19.0学习系列15:Nodejs范例(Server Received,Server Sent)
- leetcode 19. Remove Nth Node From End of List
- 七(1).DOM的核心对象:Node 分析
- dom系列:Node操作
- js-Node对象属性
- Document对象,Element对象和Node对象简介
- JavaScript HTML DOM节点类型之Node类型介绍
- 对javascriptn commonjs 和nodejs 的浅认识