【发布时间】:2021-11-01 22:05:19
【问题描述】:
我正在制作一个带有套接字的应用程序,并且需要广播信息,但仅限于房间内的人。
这是我来自server.ts的代码
// Dependencies
import express from 'express'
import http from 'http'
import socket from 'socket.io';
import {connect, disconnect, orderChanged} from './sockets/socket';
import {config} from 'dotenv';
config ();
// Main class
export default class server {
_private static instance: server
public app: express.Application
public port: number
http: http.Server private
public io: socket.Server
// Initialize variables and methods
// Singleton pattern implementation
private constructor () {
this.app = express ()
this.port = Number (process.env.SRV_PORT)
this.http = new http.Server (this.app)
this.io = new socket.Server (this.http, {
cors: {
origin: true,
credentials: true
}
})
this.listenSockets ();
}
// Return the instance running Singleton pattern
public static get instance () {
returns this._instance || (this._instance = new Server ())
}
// Method to start the server
start (callback: any) {
this.http.listen (this.port, callback)
}
private listenSockets (): void {
console.log ('Listening Sockets');
this.io.on ('connection', client => {
console.log ('Connected to room', client.rooms, '-', client.id);
// User disconnected
disconnect (client);
connect (client);
});
}
}
节点启动后,在 DP Singleton 中创建一个实例并启动套接字侦听器
当数据库中发生操作时,应用程序中的任何位置,我将其发送给调用并将信息发送到前端,前端正确接收并执行它必须做的事情。示例url / edit-products
import server from '../core/server';
// Socket broadcast, new information
const __id = String (req.headers.id);
const updatedData = await getNewData (__id);
Server.instance.io.emit ('data changed', updatedData);
问题是这个信息被不加选择地发送给所有连接到套接字的用户。现在,我有一个唯一的 ID,可以将多个用户聚集在一个 MongoDB 模型中。您可以使用该 ID 仅向具有该 ID 的用户广播。有一个逻辑暗示,如果用户从墨西哥连接,则将其添加到 MongoDB 中的 Array of people 中,否则它将添加到另一个 MongoDB 文档中,那么它们是两个不同的 ID。 我希望房间是那个 ID。
我看到我可以使用套接字的join () 方法,但该函数来自连接的客户端,而不是来自服务器本身。我尝试发布这样的信息
// Socket broadcast, new information
const __id = String (req.headers.id);
const updatedData = await getNewData (__id);
Server.instance.io.in (updatedData._id) .emit ('data changed', updatedData);
但我从来没有设置过那个“房间”。当用户登录时,他可以添加它但我不知道如何创建自定义房间,他尝试了这样的事情
const user = await UserModel.find (_data);
Server.instance.io.join (user.channel._id);
但是 io 中的那个函数不存在。
它存在这种方式,但它对我不起作用
Server.instance.io.on ('user-join', (socket: Socket) => {
console.log (plug);
socket.join (uuid);
});
Server.instance.io.emit ('user join');
我能做什么?
【问题讨论】:
标签: node.js typescript express socket.io