socket.io 消息不是广播机制

背景

以为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);
	});
});
相关推荐
人工智能训练师1 小时前
Ubuntu22.04如何安装新版本的Node.js和npm
linux·运维·前端·人工智能·ubuntu·npm·node.js
Seveny071 小时前
pnpm相对于npm,yarn的优势
前端·npm·node.js
yddddddy2 小时前
css的基本知识
前端·css
昔人'2 小时前
css `lh`单位
前端·css
Nan_Shu_6144 小时前
Web前端面试题(2)
前端
知识分享小能手4 小时前
React学习教程,从入门到精通,React 组件核心语法知识点详解(类组件体系)(19)
前端·javascript·vue.js·学习·react.js·react·anti-design-vue
蚂蚁RichLab前端团队5 小时前
🚀🚀🚀 RichLab - 花呗前端团队招贤纳士 - 【转岗/内推/社招】
前端·javascript·人工智能
孩子 你要相信光5 小时前
css之一个元素可以同时应用多个动画效果
前端·css
huangql5205 小时前
npm 发布流程——从创建组件到发布到 npm 仓库
前端·npm·node.js
Days20505 小时前
LeaferJS好用的 Canvas 引擎
前端·开源