背景
以为websocket server 的信息是广播给所有的websocket client 的,但是后续发现当一个client 发起一个操作,然后emit 一个message, 这个时间在所有client 端都有监听,但是只有发起的client 端才能接受到这个emitted msg, 而不是我之前想的,所有监听这个时间的client 都能收到。
环境
frontend项目中安装了socket.io-client
javascript
import { Socket, io } from 'socket.io-client';
private socketUrl = 'ws://localhost:3000';
private currentSocket = io(this.socketUrl);
ngOnInit() {
this.currentSocket.on('news', (result) => {
console.log(`latest news`, result.data);
});
}
backend server 中安装了socket.io, 提供websocket 连接。
javascript
import { createServer } from 'http';
import { Server } from 'socket.io';
const socketMessageIds = {
on: {
getNews: 'getNews',
addNew: 'addNew',
},
emit: {
news: 'news'
}
};
function getSuccessResponse(message, data = null) {
return {
code: 2000,
data,
msg: String(message || '')
};
}
function getErrorResponse(message, code = -1) {
return {
code,
data: null,
msg: String(message || '')
};
}
const httpServer = createServer();
const io = new Server(httpServer, {
cors: {
origin: '*'
}
});
httpServer.listen(3000);
const news = [];
io.on('connection', (socket) => {
socket.on(socketMessageIds.on.getNews, () => {
socket.emit(
socketMessageIds.emit.news,
getSuccessResponse('send msg successfully~', news)
);
});
socket.on(socketMessageIds.on.addNew, (arg: string) => {
news.push(arg);
socket.emit(
socketMessageIds.emit.news,
getSuccessResponse('send msg successfully~', news)
);
});
}
});
另外启动了一个socket.io-client 进程
javascript
import { io } from 'socket.io-client';
const socket = io('ws://localhost:3000');
socket.on('disconnected', () => {
console.log('disconnected with server');
})
socket.on('connect', () => {
socket.emit('addNew', 'dongyuhui is the new VP of dongfang zhenxuan' , (res) => {
console.log(`latest news`, res.data);
});
socket.on('news', (res) => {
console.log('latest news: ', res.data);
});
});