服务端
新建文件夹
cnpm init - y
cnpm i express --save
cnpm i koa--save
cnpm i socket.io--save
只是模拟看效果使用
const WebSocket =require('ws');const wss = new WebSocket.Server({ port:8081});//设置端口
wss.on('connection', function connection(ws){//对‘conntection’这个串进行监听,当收到这个后,执行下面的操作
ws.on('message', function incoming(message){
console.log('received: %s', message);});//下面是我写的测试数据,按需取吧
let i =0;
let j =0;setInterval(()=>{//因为模拟实时推送数据,所以用了一个定时器推送if(++i >=5){
i = i%5;}
let x =parseInt(Math.random()*5+1);
let data ={"pos_y":400+x,"pos_z":0,"pos_x":300+x,"is_online":true,"team":"红队","userName":"测试00"+i,"userid":"1"+i};
let datas ={"msg":"成功","code":"000000","data":data,"type":"LOCATION"};
ws.send(JSON.stringify(datas))//发送数据},1000);})