1、WebSocket必须要与服务器连接,所以这里采用node起服务,这里用到了ws,,也有人用nodejs-websocket

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、开始聊天

    

代码地址:https://gitee.com/muand/websocket.git

  

  

nodejs加WebSocket,聊天工具的更多相关文章

  1. nodejs+websocket聊天工具

    该聊天工具,使用nodejs起服务,websocket前端页面,聊天工具,,可以有任意多的人数参与聊天,里面的用户ID为模拟ID. 先上图 文件夹结构, 1.安装ws模块,npm install ws ...

  2. nodejs+mongoose+websocket搭建xxx聊天室

    简介 本文是由nodejs+mongoose+websocket打造的一个即时聊天系统:本来打算开发一个类似于网页QQ类似功能的聊天系统,但是目前只是开发了一个模块功能 --- 类似群聊的,即一对多的 ...

  3. 基于Nodejs开发的web即时聊天工具

    由于公司需要开发web即时聊天的功能,开始时我们主要的实施方法是用jquery的ajax定时(10秒)轮询向服务器请求,由于是轮询请求,对 服务器的压力比较大.我们网站上线的时间不长,访问量不是很大, ...

  4. nodejs与websocket模拟简单的聊天室

    nodejs与websocket模拟简单的聊天室 server.js const http = require('http') const fs = require('fs') var userip ...

  5. h5聊天工具的开发过程及思路

    这个产品的主要技术栈有,网易nim即时通信,vue-cli,muse-ui 1.在拿到这个需求时,脑袋里空的,什么想法都没有,完全懵逼,进了网易云通信的官网api查看,由于我做的是客户端的,所以重点看 ...

  6. Win7搭建nginx+php+mysql开发环境以及websocket聊天实例测试

    Win7搭建nginx+php+mysql开发环境以及websocket聊天实例测试一.下载相关安装包 1.下载nginx最新版本(nginx1.3.13版之后才支持websocket协议) 下载地址 ...

  7. Python3 实现简易局域网视频聊天工具

    Python3 实现简易局域网视频聊天工具   1.环境 操作系统为 Ubuntu 16.04 python 3.5opencv-python 3.4.1.15numpy 1.14.5PyAudio ...

  8. 基于nodejs的websocket通信程序设计

    网络程序设计无疑是nodejs + html最好用 一.nodejs的安装 1.在ubuntu上的安装 sudo apt install nodejs-legacy sudo apt install ...

  9. 使用.NET Core和Vue搭建WebSocket聊天室

    博客地址是:https://qinyuanpei.github.io.  WebSocket是HTML5标准中的一部分,从Socket这个字眼我们就可以知道,这是一种网络通信协议.WebSocket是 ...

随机推荐

  1. python基础---->python的使用(三)

    今天是2017-05-03,这里记录一些python的基础使用方法.世上存在着不能流泪的悲哀,这种悲哀无法向人解释,即使解释人家也不会理解.它永远一成不变,如无风夜晚的雪花静静沉积在心底. Pytho ...

  2. Elasticsearch学习之深入搜索四 --- cross-fields搜索

    1. cross-fields搜索 一个唯一标识,跨了多个field.比如一个人,标识,是姓名:一个建筑,它的标识是地址.姓名可以散落在多个field中,比如first_name和last_name中 ...

  3. 题目1448:Legal or Not(有向无环图判断——拓扑排序问题)

    题目链接:http://ac.jobdu.com/problem.php?pid=1448 详解链接:https://github.com/zpfbuaa/JobduInCPlusPlus 参考代码: ...

  4. 让google.com不跳转到google.com.hk

    自从google的服务器搬离中国大陆后,大陆地区用户用google服务时会自动跳转到香港的http://google.com.hk,,有关键字过滤而且偶尔不是很稳定,这对我们的生活工作都造成了困扰. ...

  5. Word插入htm文件导致文本域动态增加的一个问题

    受html标签影响,超链接也会被变成文本域(HYPERLINK).当遍历文本域进行替换之前如果预存了文本域的数量(Count/Length/etc.)将导致遗漏.

  6. 关于sizeof和strlen

    已知 char *str1="absde"; char str2[]="absde"; char str3[8]={'a',}; char ss[] = &qu ...

  7. Android 浅谈 设计与屏幕适配 【1.6235449734285716】

    extends: http://www.ui.cn/detail/45435.html http://www.2cto.com/kf/201501/372699.html http://www.cnb ...

  8. 9.8Django

    2018-9-8 14:34:38

  9. ActiveMQ延迟消息配置

    ActiveMQ使用延迟消息,需要在activemq.xml配置文件中添加这项: schedulerSupport="true" <broker xmlns="ht ...

  10. Oracle数据库查询表信息/列信息(列ID/列名/数据类型/长度/精度/是否可以为null/默认值/是否自增/是否是主键/列描述)

    查询表信息(表名/表描述) Select table_Name As Name,Comments As Value From User_Tab_Comments Where table_Type='T ...