nodejs+websocket聊天工具

该聊天工具,使用nodejs起服务,websocket前端页面,聊天工具,,可以有任意多的人数参与聊天,里面的用户ID为模拟ID。

先上图

文件夹结构,

1、安装ws模块,npm install ws

2、web.js文件,是Nodejs后端代码

var WebSocketServer = require(‘ws‘).Server,
wss = new WebSocketServer({ port: 8181 });

//var client1 = null,client2=null,client1Ready = false, client2Ready = false;

var config = {};
var userList = {};

wss.on(‘connection‘, function (ws) {
    console.log(‘client connected‘);
    ws.on(‘message‘, function (message) {

      var data = JSON.parse(message);
      console.log(data);
      if(data.type == ‘register‘){
      	console.log("register");

      	config[data.meID]  =  {
			ID:data.meID,
			myNike:data.sendNike,
			pipe:ws,
			Ready:true
		};
      	userList[data.meID] = {
			ID: data.meID,
			myNike: data.sendNike
		};
      	refreshList();

      }else if(data.type == ‘sendMessage‘){
      	console.log("send");
      	sendMessage(data);
      }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;
    			delete config[i];
    			delete userList[i];
    			refreshList();
    			break;
    		}
    	}
    	console.log("关闭链接");
    });

});

//更新聊天列表
function refreshList(){
	for(var i in config){
		config[i].pipe.send(JSON.stringify({
			‘type‘:‘refreshList‘,
			‘list‘:userList
		}));
	}
}

//更新聊天

function sendMessage(data){
	if(config[data.receiveID]){
		//对方在线
		data.sendNike = userList[data.meID].myNike;

		config[data.meID].pipe.send(JSON.stringify(data));
		config[data.receiveID].pipe.send(JSON.stringify(data));

	}else{
		//对方不在线
		config[data.meID].pipe.send(JSON.stringify({"error":true}));
	}

}

//npm install ws

  

2、添加客户端client.html

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>client1</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: right;
			color: deeppink;
		}
		#chat p.receive{
			text-align:left ;
		}
		.btn{
			text-align: center;
		}
		.showState{
			text-align: center;
		}
		.showInfo{
			text-align: center;
		}
		div.firend{
			width: 200px;
		}
		div.firend p{
			height: 30px;
			text-align: center;
			line-height: 30px;
			background: deeppink;
			color: #fff;
		}
		ul.list{
			width: 200px;

		}
		ul.list li{
			height: 30px;
			line-height: 30px;
			background: #9ACD32;
			color: #fff;
			text-align: center;
			border: 1px solid #000;
			cursor: pointer;
			position: relative;
		}
		ul.list li span{
			position: absolute;
			width: 20px;
			height: 20px;
			text-align: center;
			line-height: 20px;
			font-size: 14px;
			border-radius: 10px;
			background: red;
			color: #fff;
			right: -10px;
			top: 5px;
			display: none;
		}
	</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>
<div class="firend">
	<p>在线好友列表</p>
	<ul class="list">

	</ul>
</div>

</body>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">

	var sendConfig = {
		"type":"send",
		"meID":getName(),
		"sendNike":"client1",
		"receiveNike":"",
		"receiveID":‘‘
	};

	var register = {
		"type":"register",
		"sendNike":sendConfig.sendNike,
		"meID":sendConfig.meID
	}
	var messageList = {};

	//随机获取名称
	function getName() {
		var timer = new Date();
		var arr = JSON.stringify(timer).replace(/:|-|"/g, ‘‘).split(‘.‘);
		var str = arr.join(‘‘);
		console.log(str);
		return str;
	}

	var mes = document.getElementById("message");
	var box = $("#chat");
	var chatWith = $(".showInfo");
	var showState = $(".showState");
	var personList = $(".list");

	var ws = new WebSocket("ws://localhost:8181");
	ws.onopen = function (e) {
		ws.send(JSON.stringify(register));
		showState.html("链接成功!");
		// chatWith.html("你正在和:"+ sendConfig.receiveNike + "聊天");
	}

	//接收聊天信息
	ws.onmessage=function (e) {
		var data = JSON.parse(e.data);

		if(data.type == ‘refreshList‘){
			refreshList(data.list);
		}else if(data.type == ‘sendMessage‘){
			messageStore(JSON.parse(e.data));
		}

	};

	//记录消息通信
	function  messageStore(data) {
		var recodeId1 = data.receiveID + "&" + data.meID;
		var recodeId2 = data.meID  + "&" + data.receiveID;
		if(messageList[recodeId1]){
			messageList[recodeId1].push(data);
		}else if(messageList[recodeId2]){
			messageList[recodeId2].push(data);
		}else{
			messageList[recodeId1] = [];
			messageList[recodeId1].push(data);
		}
		//create(data);
		alertmessage(data);
	}
	//提示消息来了
	function alertmessage(data) {
		var liList = $(‘ul.list‘).find(‘li‘);
		for(var i = 0; i < liList.length ; i++ ){
			if(liList.eq(i).attr(‘userId‘) == data.meID){ //找到对应的消息接收者
				if(data.meID != sendConfig.meID){   //排除自己
					if(data.meID != sendConfig.receiveID){  //排除正在聊天的人
						var $span = 	liList.eq(i).find(‘span‘);
						$span.css(‘display‘,‘block‘);
						$span.html($span.html()*1+1);
					}else{
						create(data);
					}
				}else{
					create(data);
				}
				break;
			}
		}
	}

	//更新好友列表
	function refreshList(data){
		console.log(data);
		personList.html(‘‘);
		for(var  i in data){
			if(data[i].ID == sendConfig.meID){
				personList.append(‘<li userId =‘ + data[i].ID  + ‘ > <strong>自己 </strong> <span>0</span> </li>‘)

			}else{
				personList.append(‘<li userId =‘ + data[i].ID  + ‘ ><strong>‘+ data[i].myNike  +‘</strong><span>0</span></li>‘)

			}

		}
	}
	//选择聊天对象
	$(".list").on("click","li",function(){
		box.html(‘‘);
		chatWith.html("你正在和:"+ $(this).find(‘strong‘).html() + "聊天");
		sendConfig.receiveID = $(this).attr(‘userId‘);
		//取出聊天记录
		var recodeId1 = sendConfig.receiveID + "&" + sendConfig.meID;
		var recodeId2 = sendConfig.meID  + "&" + sendConfig.receiveID;
		if(messageList[recodeId1]){
			getMessageRecod( messageList[recodeId1]);
		}else if(messageList[recodeId2]){
			getMessageRecod( messageList[recodeId2]);
		}

		//隐藏消息提示
		$(this).find(‘span‘).css(‘display‘,‘none‘).html(‘0‘);

	});

	//取出聊天记录,并且渲染
	function  getMessageRecod(data) {
		if(data){
			for(var i = 0; i < data.length ; i++){
				create(data[i]);
			}
		}
	}
	//创建标签
	function create(data){
		if(data.error){
			alert("发送失败,对方不在线!");
		}else {
			if (data.meID == sendConfig.meID) {
				box.append("<p class=‘send‘>" + sendConfig.sendNike + ":" + data.message + "</p>");
			} else {
				box.append("<p class=‘receive‘>" + data.sendNike + ":" + data.message + "</p>");
			}
		}
	}

	//发送聊天信息
	function sendMessage() {
		if(sendConfig.receiveID == ‘‘){
			alert(‘没有选择发送消息对象!‘);
		}else{
			var mesage = {
				"type":"sendMessage",
				"meID":sendConfig.meID,
				"receiveID":sendConfig.receiveID,
				"message":mes.value,
			};
			var str = JSON.stringify(mesage);
			ws.send(str);
		}
	}

</script>
</html>

  3、添加客户端,client2.html,client3.html,,,只需要修改client1.html中,config的sendNick如图,

4、注意添加jquery文件

5、nodejs启动web.js文件,打开所有.html文件,进行聊天。

时间: 2024-08-03 10:34:43

nodejs+websocket聊天工具的相关文章

nodejs websocket 聊天应用

前端一直是一块充满惊喜的土地,不仅是那些富有创造性的页面,还有那些惊赞的效果及不断推出的新技术.像node.js这样的后端开拓者直接将前端人员的能力扩大到了后端.瞬间就有了一统天下的感觉,来往穿梭于前后端之间代码敲得飞起,从此由前端晋升为'前后端'. 图片来自G+ 本文将使用Node.js加web socket协议打造一个网页即时聊天程序,取名为HiChat,中文翻过来就是'嗨聊',听中文名有点像是专为寂寞单身男女打造的~ 其中将会使用到express和socket.io两个包模块,下面会有介绍

使用PHP+Swoole实现的网页即时聊天工具:PHPWebIM

使用PHP+Swoole实现的网页即时聊天工具 全异步非阻塞Server,可以同时支持数百万TCP连接在线 同时支持websocket+comet2种兼容协议,可用于所有种类的浏览器包括IE 拥有完整的UI界面 支持单聊/群聊/组聊等功能 支持发送表情 支持永久保存聊天记录 基于Server PUSH的即时内容更新,登录/登出/状态变更/消息等会内容即时更新 最新的版本已经可以原生支持IE系列浏览器了,基于Http长连接 安装 swoole扩展 pecl install swoole swool

(18)c++项目练习一(功能会不断扩展)--------【聊天工具】

1.准备使用Qt和C++做一个远程(基于互联网的)聊天工具,需要实现以下功能 (1)多对多聊天功能 (2)文件传输功能 (3)注册.登录功能 (4)加好友.同意好友功能 (5)好友列表.黑名单功能(分组功能) (6)语音聊天功能 (7)表情发送功能 2.UML类图设计

Web版的各种聊天工具

直到近期为止,我们经常使用的即时聊天工具(QQ.msn等)了Web版,大家不用下载庞大软件,直接打开网页就能够与自己的好友聊天,非常方便.在此将时汇总 ?????? 便于大家查找 ?????? 节约大家一点时间 此都是官方站点 ?????? 请大家放心使用: 1.先说我们最经常使用的QQ 在线聊天Web版地址: http://webqq.qq.com/ (刚建的 ?????? 现正在測试 ?????? 须要申请 ?????? 日前还不太稳定 ?????? 有待完好) 2.msn在线聊天Web版地

ios开发xmpp仿微信即时聊天工具

最近在做一个项目,需要一个即时聊天工具,先打算有第三方环信(http://www.easemob.com),但是最终老板不允许,要自己开发用自己的服务器,哎!如果有需要的可以去看看这个环信,真的不错.进入今天的主题,其实也是大神们开发的,我在这只是把一些细节理一下让大家你能少走一点弯路,需要的资料和源码这里面都有http://pan.baidu.com/s/1nt5esnn. 详细的介绍看这http://blog.csdn.net/kangx6/article/details/7740135,看

关于Socket编写简单聊天工具的总结(原创)

这段时间再看socket编程,虽然现在是刚刚接触,但是还是忍不住想写一篇总结,来激励自己努力学习,写的不好的地方,还请大家指教啊! 下面针对一个简单的发送消息和文件的程序说说吧.   首先是服务器需要准备二个Socket和二个Thread如下: //和客户机进行通信 private Socket sckCommit; //监听客户机 private Socket sckListen; private Thread thdListen; private Thread thdCommit; 对客户机

基于文件形式的聊天工具

前因 由于在甲方公司领导要求,在上班时禁止一切的聊天工具的出现.各种封IM软件或者端口.但是开发人员和测试人员相隔半天街,所以,一直想整个简单且不用网络的聊天的工具. 思索半天,遇到以下问题: 我们方的IP地址和甲方人员的不是同网段的 每次交流,除了邮件,就是靠吼 几个人用的系统有几种:xp,win8, win7, mac 网段不一样,某些内网,我们外部不能访问 有以下共同点: 都可以访问某个服务器(因为得时不时看下测试日志) 都会基础的Linux命令 简单,又不用网络的,到底可以做神马呢? 就

Netty 实现 WebSocket 聊天功能

准备 JDK 7+ Maven 3.2.x Netty 4.x Eclipse 4.x WebSocket WebSocket 通过"Upgrade handshake(升级握手)"从标准的 HTTP 或HTTPS 协议转为 WebSocket.因此,使用 WebSocket 的应用程序将始终以 HTTP/S 开始,然后进行升级.在什么时候发生这种情况取决于具体的应用;它可以是在启动时,或当一个特定的 URL 被请求时. 在我们的应用中,当 URL 请求以"/ws"

基于Java NIO的多人在线聊天工具源码实现(登录,单聊,群聊)

近来在学习Java NIO网络开发知识,写了一个基于Java NIO的多人在线聊天工具练练手.源码公开在Coding上: https://coding.net/u/hust_wsh/p/MyChat/git ,开发环境是Ubuntu14.04+Eclipse Mars+JDK1.8. 要想编写一个基于Java NIO的多人在线聊天工具,我总结需要以下几方面的地址:客户端服务器模型,Java NIO中的Selector,SocketChannel,ByteBuffer,Collections以及序