nodejs加WebSocket,聊天工具
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,聊天工具的更多相关文章
- nodejs+websocket聊天工具
该聊天工具,使用nodejs起服务,websocket前端页面,聊天工具,,可以有任意多的人数参与聊天,里面的用户ID为模拟ID. 先上图 文件夹结构, 1.安装ws模块,npm install ws ...
- nodejs+mongoose+websocket搭建xxx聊天室
简介 本文是由nodejs+mongoose+websocket打造的一个即时聊天系统:本来打算开发一个类似于网页QQ类似功能的聊天系统,但是目前只是开发了一个模块功能 --- 类似群聊的,即一对多的 ...
- 基于Nodejs开发的web即时聊天工具
由于公司需要开发web即时聊天的功能,开始时我们主要的实施方法是用jquery的ajax定时(10秒)轮询向服务器请求,由于是轮询请求,对 服务器的压力比较大.我们网站上线的时间不长,访问量不是很大, ...
- nodejs与websocket模拟简单的聊天室
nodejs与websocket模拟简单的聊天室 server.js const http = require('http') const fs = require('fs') var userip ...
- h5聊天工具的开发过程及思路
这个产品的主要技术栈有,网易nim即时通信,vue-cli,muse-ui 1.在拿到这个需求时,脑袋里空的,什么想法都没有,完全懵逼,进了网易云通信的官网api查看,由于我做的是客户端的,所以重点看 ...
- Win7搭建nginx+php+mysql开发环境以及websocket聊天实例测试
Win7搭建nginx+php+mysql开发环境以及websocket聊天实例测试一.下载相关安装包 1.下载nginx最新版本(nginx1.3.13版之后才支持websocket协议) 下载地址 ...
- Python3 实现简易局域网视频聊天工具
Python3 实现简易局域网视频聊天工具 1.环境 操作系统为 Ubuntu 16.04 python 3.5opencv-python 3.4.1.15numpy 1.14.5PyAudio ...
- 基于nodejs的websocket通信程序设计
网络程序设计无疑是nodejs + html最好用 一.nodejs的安装 1.在ubuntu上的安装 sudo apt install nodejs-legacy sudo apt install ...
- 使用.NET Core和Vue搭建WebSocket聊天室
博客地址是:https://qinyuanpei.github.io. WebSocket是HTML5标准中的一部分,从Socket这个字眼我们就可以知道,这是一种网络通信协议.WebSocket是 ...
随机推荐
- 【大数据系列】安装Ambari
一.Ambari简介 The Apache Ambari project is aimed at making Hadoop management simpler by developing soft ...
- chorme 浏览器记住密码后input黄色背景处理
使用chrome浏览器选择记住密码的账号,输入框会自动加上黄色的背景,有些设计输入框是透明背景的,需要去除掉这个黄色的背景: 方法1:阴影覆盖 input:-webkit-autofill { -we ...
- css3整理--text-overflow
text-overflow语法: text-overflow : clip | ellipsis clip:表示不显示省略标记(...),而只是简单的裁切,需要在一定的高度范围内配合overflow: ...
- yum配置与使用(很详细)
yum的配置一般有两种方式,一种是直接配置/etc目录下的yum.conf文件,另外一种是在/etc/yum.repos.d目录下增加.repo文件.一.yum的配置文件 $ cat /etc/yum ...
- 【 转】__try,__except,__finally,__leave异常模型机制
转自:http://blog.csdn.net/wwl33695/article/details/8686458 导读: 从本篇文章开始,将全面阐述__try,__except,__finally,_ ...
- mysql概要(十四)(二)索引(补充:外键级联操作)
[ ON DELETE { NO ACTION | CASCADE | SET NULL | SET DEFAULT } ] [ ON UPDATE { NO ACTION | CASCADE | S ...
- JavaEE Cookie HttpSession 学习笔记
1. 会话管理概述 1.1 什么是会话 好比一次通话.打开浏览器,点击多次链接(发出多次请求和收到多次的响应),关闭浏览器,这个过程就是一次会话. 有功能 可以 文件 新建会话 1.2 解决的问题是 ...
- ELK之filebate收集日志传递至Logstash
软件版本查看(版本最好一致) 安装过程不详叙 本次使用filebeat监控nginx日志(已经配置json输出)收集并且传递给Logstash进行处理 filebeat配置文件/etc/filebea ...
- ZOJ 4029 - Now Loading!!! - [前缀和+二分]
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=4029 Time Limit: 1 Second Memory L ...
- 自己封装framworks上传到应用商店报错
参考链接: http://www.jianshu.com/p/60ac3ded34a0 http://ikennd.ac/blog/2015/02/stripping-unwanted-archite ...