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{
				 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{
				 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

  

  

原文地址:https://www.cnblogs.com/muamaker/p/6277748.html