| (1):搭建nodejs服务器以后,cnpm install nodejs-websocket进行安装这个模块,会生成一个node_modules文件夹
  (2)创建websocket服务器app.js:
 
const ws = require('nodejs-websocket')
var server = ws.createServer((conn)=>{
   console.log('有用户连接上来了')
   conn.on('text',(data)=>{
   		console.log('接收到用户信息:',data)
   });
})
ws.addEventListener('message',(e)=>{
	console.log(e.data)
});
server.listen(3000,()=>{
	console.log('websocket server starting')
})
 (3)创建客户端index.html文件 <!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
	<style type="text/css">
		div{
			width: 200px;
			height: 200px;
			border: 1px solid black;
		}
	</style>
</head>
<body>
<input type="text" placeholder="输入信息..."/>
<button>发送</button>
<div></div>
<script>
var divHtml =  document.querySelector('div');
var buttonHtml =  document.querySelector('button');
var inputHtml = document.querySelector('input');
var ws = new WebSocket("ws://localhost:3000");
 
ws.addEventListener('open',function(){
     divHtml.innerHTML = '已经连接成功';
})
buttonHtml.addEventListener('click',()=>{
  var value = inputHtml.value;
  ws.send(value);
});
</script>
</body>
</html>
 测试:
  |