使用websocket
一.建立scoket服务
yarn add ws
const WebSocket = require('ws');
// 定义websocket服务器
const wsServer = new WebSocket.Server({ port: 5000 });
// 定义连接到的websocket集合
let socketSet = [];
// 连接
wsServer.on('connection', (websocket, req, res) => {
console.log('进入',req.url)
const userid = req.url.split('/');
let isExist = false; // 标记当前用户是否在线
socketSet.forEach(ws => {
if (ws.currentId == userid[1]) isExist = true;
});
if (!isExist) {
socketSet.push({
websocket: websocket,
currentId: userid[1]
});
}
wsServer.on('close',(websocket,req,res)=>{
console.log('退出')
})
websocket.on('message', function incoming(message) {
// console.log('received: %s', message);
// 收到消息之后推送给目标对象
const msgObj = JSON.parse(message);
socketSet.forEach(ws => {
if (ws.websocket.readyState == 1) {
if (ws.currentId == msgObj.target) {
// 判断当前用户是否为目标对象
ws.websocket.send(
JSON.stringify({
msg: msgObj.msg,
from: msgObj.current
})
);
}
}
});
});
// websocket.send(
// JSON.stringify({
// msg: 'websocket连接成功'
// })
// );
});
/**
readyState属性返回实例对象的当前状态,共有四种。
CONNECTING:值为0,表示正在连接。
OPEN:值为1,表示连接成功,可以通信了。
CLOSING:值为2,表示连接正在关闭。
CLOSED:值为3,表示连接已经关闭,或者打开连接失败
*/
1.广播消息
const ws=new WebSocket.Server({
port:5001
})
ws.on('connection',(socket,req,res)=>{
socket.on('message', function incoming(data) {
ws.clients.forEach(client=>{
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
})
})
})
二.建立连接
export default { // 保证整个项目只有一个socket实例 ws: null, // Websocket实例 init(config, onMessage, onError) { if (!this.ws) { // 实例化socket对象 this.ws = new WebSocket(`ws://localhost:5000/${config.user.id}`); } // 客户端接收消息 this.ws.onmessage = event => { let message = JSON.parse(event.data); onMessage && onMessage(message); // 接收到消息触发的回调 }; // 出错 this.ws.onerror = error => { onError && onError(error); }; // this.ws.onclose = () => { // console.log('close') // this.ws = null; // }; }, send(msgObj) { // 发送消息的时候触发 this.ws.send(JSON.stringify(msgObj)); }, };
浙公网安备 33010602011771号