IT虾米网

1.用node搭建本地服务

npm install nodejs-websocket

	var ws = require("nodejs-websocket"); 
	var server = ws.createServer(function(conn){ 
	console.log('New Connection!'); 
	conn.on('text',function(str){ 
		console.log('receive' + str); 
		conn.sendText(str.toUpperCase() + '!!!'); 
	}) 
	conn.on('close',function(code,reason){ 
		console.log('Connection closed'); 
	}) 
 
	//服务出现错误时用来处理错误,如果不加出现错误服务就会挂掉 
	// conn.on('error',function(err){ 
	// 	console.log('handle error'); 
	// 	console.log(err); 
	// }) 
	}).listen('3000');                                                                                                                                                        
	console.log('node websocket run listening on port 3000') 

客户端代码实现

	<!DOCTYPE html> 
	<html lang="en"> 
 
		<head> 
   		 	<meta charset="UTF-8"> 
    		<title>websocket测试</title> 
   		    <style> 
   				 input { 
       	         outline: none; 
                } 
 
    			.content { 
        		margin-top: 20px; 
        		width: 300px; 
      			min-height: 100px; 
      		    border: 1px solid blue; 
    			} 
    	</style> 
	</head> 
 
	<body> 
    	<h3>websocket演示</h3> 
   	    <input type="text" id='txt'> 
        <button id='sendTxt'>发送</button> 
        <div class='content' id='receiveMsg'></div> 
    	<script> 
    		var websocket = new WebSocket('ws://localhost:3000/'); 
   		    websocket.onopen = function() { 
            console.log('websocket open'); 
            document.getElementById('receiveMsg').innerHTML = 'Connected'; 
            }; 
            websocket.onclose = function() { 
            console.log('websocket close'); 
            }; 
            websocket.onmessage = function(e) { 
            console.log(e); 
            document.getElementById('receiveMsg').innerHTML = e.data; 
         
           }; 
    	   document.getElementById('sendTxt').onclick = function() { 
           var txt = document.getElementById('txt').value; 
           websocket.send(txt); 
         }; 
    </script> 
</body> 
 
</html> 
 
 

简单的websocket应用,只是将客户端收到的信息发送到服务端,将原字符串转化为大写后加上三个!!!后返回;

改进后的代码如下:

服务端代码:

客户端代码:

有点:加入了进入聊天室,离开聊天室等字段,并对每一个连接的客户端做了简单的区分;

缺点:服务端和客户端只是简单的基于字符串的交互,没有对数据的属性进行区分,相对简单;

服务端代码:

客户端代码:

有点:在服务端对消息的属性进行了包装,并在客户端进行不同效果的展示,在服务端需要将对象转化为字符串才能发送到客户端,不够灵活;

最终效果:


评论关闭
IT序号网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!