代码改变世界

nodejs+websocket聊天工具

2017-06-27 12:22  muamaker  阅读(419)  评论(0编辑  收藏  举报

该聊天工具,使用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文件,进行聊天。