开局一个项目,咱们先给项目装一个nodeJs的模块,叫nodejs-websocket ,
npm install nodejs-websocket
服务端
var ws = require("nodejs-websocket")
var index = 0;
let IndexNum;
var server = ws.createServer(function(conn) {
console.log("New connection")
//conn.on("***",function(){}) 绑定事件(***)及事件的处理程序
conn.on("text", function(str) {//事件:“ text(str)”收到文本时发出。str是一个字符串
console.log(str);
if(str == 1 ){
IndexNum = setInterval(()=>{
let mes = {};
mes.index = index++;
mes.number = parseInt (Math.random()*100);
//JSON.stringify(mes)系列化对象,把对象的类型转换为字符串类型
conn.sendText(JSON.stringify(mes));//将给定的字符串发送到前端
},1000);
}else{
conn.sendText('erro');
}
})
conn.on("close", function(code) {//开始关闭握手(发送关闭帧)
console.log("关闭",code);
clearInterval(IndexNum);
})
conn.on("error", function(err) {//发生错误时发出。如果握手无效,也会发出响应。
console.log(err);
})
}).listen(3000);//服务器监听端口3000
console.log("websocket server running on port: 3000");
客户端
<body>
<button onclick="begin()">开始</button>
<button onclick="stop()">停止</button>
<div class="box"></div>
<script type="text/javascript">
var websocket = new WebSocket("ws://localhost:3000/");
var box = document.getElementsByClassName('box')[0];
websocket.onopen = function() {
console.log("连接成功");
}
websocket.onclose = function() {
console.log("websocket close");
}
function begin(){
websocket.send(1);
}
function stop(){
websocket.close();
}
// 只接收字符串参数,所以在服务端相传对象过来可以用JSON先转换成字符串,然后在这边转成对象
websocket.onmessage = function(e) {
let data = JSON.parse(e.data);
let text = `<li>第${data.index}次,数字是${data.number};</li>`
box.innerHTML += text;
}
</script>
</body>