- vue代码
- 需要安装 $ cnpm install websocket --save
<template>
<div id="app">
</div>
</template>
<script>
export default {
data() {
return {};
},
methods: {
initWebSocket() {
this.websock = new WebSocket("ws://localhost:8081"); //这个连接ws://固定,后面的根据自己的IP和端口进行改变,我设置监听的就是8081
this.websock.onmessage = this.websocketonmessage;
this.websock.onerror = this.websocketonerror;
this.websock.onopen = this.websocketonopen;
this.websock.onclose = this.websocketclose;
},
websocketonopen() {
// 连接建立之后执行send方法发送数据,这个和自己的后端沟通好需要传什么数据,我的是要进行token验证
// let token = sessionStorage.getItem("token");
// let data = {
// type: "REGISTER",
// data: { token: token },
// };
// this.websock.send(JSON.stringify(data));
this.websock.send("connection");
},
websocketonerror() {
//连接错误
console.log("WebSocket连接失败");
},
websocketonmessage(e) {
// 数据接收
console.log(JSON.parse(e.data));
},
websocketclose(e) {
// 关闭连接
console.log("已关闭连接", e);
},
ceshi(){
this.websock.send("connection");
}
},
mounted(){
this.initWebSocket(); //页面渲染的时候,对ws进行初始化
},
destroyed() {
this.websock.close(); // 页面销毁后断开websocket连接
},
};
</script>
服务端
新建文件夹
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);
})
版权声明:本文为YhWyl527原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。