没有收到发送到房间的套接字消息,但可以广播

时间:2019-06-12 21:41:00

标签: node.js socket.io

我有一个nodejs(10.16)/ express(4.16)作为后端,而React Native 0.59作为前端应用程序。 socket.io是版本2.2.0。前端应用程序将事件消息发送到后端,后端服务器将消息转发到与eventID相同的room#。

这是后端服务器上发出消息的代码:

    const socket = req.app.get('socket');
    const room = msg.event_id.toString();
    socket.join(room);
    socket.to(room).emit("event message", msg);

这里,服务器将客户端套接字连接到房间,并在收到新消息时将消息发送到room。问题是其他连接的前端未收到该消息。但是在后端服务器上,如果我更改为广播,则其他已连接的前端应用程序确实收到了消息:

socket.broadcast.emit("event message", msg); 

如何仅将消息发送到房间?

更新:套接字的输出(“ 1”是房间名称):

socket in new message :  Socket {
  nsp:
   Namespace {
     name: '/',
     server:
      Server {
        nsps: [Object],
        parentNsps: Map {},
        _path: '/socket.io',
        _serveClient: true,
        parser: [Object],
        encoder: Encoder {},
        _adapter: [Function: Adapter],
        _origins: '*:*',
        sockets: [Circular],
        eio: [Server],
        httpServer: [Server],
        engine: [Server] },
     sockets:
      { 'v-Ai6mJHgYdLwvVGAAAC': [Socket],
        xwVZDqAT2qorua6dAAAD: [Circular] },
     connected:
      { 'v-Ai6mJHgYdLwvVGAAAC': [Socket],
        xwVZDqAT2qorua6dAAAD: [Circular] },
     fns: [],
     ids: 0,
     rooms: [],
     flags: {},
     adapter:
      Adapter {
        nsp: [Circular],
        rooms: [Object],
        sids: [Object],
        encoder: Encoder {} },
     _events: [Object: null prototype] { connection: [AsyncFunction] },
     _eventsCount: 1 },
  server:
   Server {
     nsps: { '/': [Namespace] },
     parentNsps: Map {},
     _path: '/socket.io',
     _serveClient: true,
     parser:
      { protocol: 4,
        types: [Array],
        CONNECT: 0,
        DISCONNECT: 1,
        EVENT: 2,
        ACK: 3,
        ERROR: 4,
        BINARY_EVENT: 5,
        BINARY_ACK: 6,
        Encoder: [Function: Encoder],
        Decoder: [Function: Decoder] },
     encoder: Encoder {},
     _adapter: [Function: Adapter],
     _origins: '*:*',
     sockets:
      Namespace {
        name: '/',
        server: [Circular],
        sockets: [Object],
        connected: [Object],
        fns: [],
        ids: 0,
        rooms: [],
        flags: {},
        adapter: [Adapter],
        _events: [Object],
        _eventsCount: 1 },
     eio:
      Server {
        clients: [Object],
        clientsCount: 2,
        wsEngine: 'ws',
        pingTimeout: 5000,
        pingInterval: 25000,
        upgradeTimeout: 10000,
        maxHttpBufferSize: 100000000,
        transports: [Array],
        allowUpgrades: true,
        allowRequest: [Function: bound ],
        cookie: 'io',
        cookiePath: '/',
        cookieHttpOnly: true,
        perMessageDeflate: [Object],
        httpCompression: [Object],
        initialPacket: [Array],
        ws: [WebSocketServer],
        _events: [Object],
        _eventsCount: 1 },
     httpServer:
      Server {
        _events: [Object],
        _eventsCount: 5,
        _maxListeners: undefined,
        _connections: 3,
        _handle: [TCP],
        _usingWorkers: false,
        _workers: [],
        _unref: false,
        allowHalfOpen: true,
        pauseOnConnect: false,
        httpAllowHalfOpen: false,
        timeout: 120000,
        keepAliveTimeout: 5000,
        maxHeadersCount: null,
        headersTimeout: 40000,
        _connectionKey: '6::::3000',
        [Symbol(IncomingMessage)]: [Function],
        [Symbol(ServerResponse)]: [Function],
        [Symbol(asyncId)]: 9 },
     engine:
      Server {
        clients: [Object],
        clientsCount: 2,
        wsEngine: 'ws',
        pingTimeout: 5000,
        pingInterval: 25000,
        upgradeTimeout: 10000,
        maxHttpBufferSize: 100000000,
        transports: [Array],
        allowUpgrades: true,
        allowRequest: [Function: bound ],
        cookie: 'io',
        cookiePath: '/',
        cookieHttpOnly: true,
        perMessageDeflate: [Object],
        httpCompression: [Object],
        initialPacket: [Array],
        ws: [WebSocketServer],
        _events: [Object],
        _eventsCount: 1 } },
  adapter:
   Adapter {
     nsp:
      Namespace {
        name: '/',
        server: [Server],
        sockets: [Object],
        connected: [Object],
        fns: [],
        ids: 0,
        rooms: [],
        flags: {},
        adapter: [Circular],
        _events: [Object],
        _eventsCount: 1 },
     rooms:
      { '1': [Room],
        'v-Ai6mJHgYdLwvVGAAAC': [Room],
        xwVZDqAT2qorua6dAAAD: [Room] },
     sids:
      { 'v-Ai6mJHgYdLwvVGAAAC': [Object],
        xwVZDqAT2qorua6dAAAD: [Object] },
     encoder: Encoder {} },
  id: 'xwVZDqAT2qorua6dAAAD',
  client:
   Client {
     server:
      Server {
        nsps: [Object],
        parentNsps: Map {},
        _path: '/socket.io',
        _serveClient: true,
        parser: [Object],
        encoder: Encoder {},
        _adapter: [Function: Adapter],
        _origins: '*:*',
        sockets: [Namespace],
        eio: [Server],
        httpServer: [Server],
        engine: [Server] },
     conn:
      Socket {
        id: 'xwVZDqAT2qorua6dAAAD',
        server: [Server],
        upgrading: false,
        upgraded: false,
        readyState: 'open',
        writeBuffer: [],
        packetsFn: [],
        sentCallbackFn: [],
        cleanupFn: [Array],
        request: [IncomingMessage],
        remoteAddress: '::ffff:192.168.2.133',
        checkIntervalTimer: null,
        upgradeTimeoutTimer: null,
        pingTimeoutTimer:
         Timeout {
           _called: false,
           _idleTimeout: 30000,
           _idlePrev: [TimersList],
           _idleNext: [Timeout],
           _idleStart: 137114,
           _onTimeout: [Function],
           _timerArgs: undefined,
           _repeat: null,
           _destroyed: false,
           [Symbol(unrefed)]: false,
           [Symbol(asyncId)]: 512,
           [Symbol(triggerId)]: 259 },
        transport: [WebSocket],
        _events: [Object],
        _eventsCount: 3 },
     encoder: Encoder {},
     decoder: Decoder { reconstructor: null, _callbacks: [Object] },
     id: 'xwVZDqAT2qorua6dAAAD',
     request:
      IncomingMessage {
        _readableState: [ReadableState],
        readable: true,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        socket: [Socket],
        connection: [Socket],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Array],
        trailers: {},
        rawTrailers: [],
        aborted: false,
        upgrade: true,
        url: '/socket.io/?EIO=3&transport=websocket',
        method: 'GET',
        statusCode: null,
        statusMessage: null,
        client: [Socket],
        _consuming: false,
        _dumped: false,
        parser: null,
        _query: [Object],
        websocket: [WebSocket] },
     onclose: [Function: bound ],
     ondata: [Function: bound ],
     onerror: [Function: bound ],
     ondecoded: [Function: bound ],
     sockets: { xwVZDqAT2qorua6dAAAD: [Circular] },
     nsps: { '/': [Circular] },
     connectBuffer: [] },
  conn:
   Socket {
     id: 'xwVZDqAT2qorua6dAAAD',
     server:
      Server {
        clients: [Object],
        clientsCount: 2,
        wsEngine: 'ws',
        pingTimeout: 5000,
        pingInterval: 25000,
        upgradeTimeout: 10000,
        maxHttpBufferSize: 100000000,
        transports: [Array],
        allowUpgrades: true,
        allowRequest: [Function: bound ],
        cookie: 'io',
        cookiePath: '/',
        cookieHttpOnly: true,
        perMessageDeflate: [Object],
        httpCompression: [Object],
        initialPacket: [Array],
        ws: [WebSocketServer],
        _events: [Object],
        _eventsCount: 1 },
     upgrading: false,
     upgraded: false,
     readyState: 'open',
     writeBuffer: [],
     packetsFn: [],
     sentCallbackFn: [],
     cleanupFn: [ [Function], [Function] ],
     request:
      IncomingMessage {
        _readableState: [ReadableState],
        readable: true,
        _events: [Object],
        _eventsCount: 1,
        _maxListeners: undefined,
        socket: [Socket],
        connection: [Socket],
        httpVersionMajor: 1,
        httpVersionMinor: 1,
        httpVersion: '1.1',
        complete: true,
        headers: [Object],
        rawHeaders: [Array],
        trailers: {},
        rawTrailers: [],
        aborted: false,
        upgrade: true,
        url: '/socket.io/?EIO=3&transport=websocket',
        method: 'GET',
        statusCode: null,
        statusMessage: null,
        client: [Socket],
        _consuming: false,
        _dumped: false,
        parser: null,
        _query: [Object],
        websocket: [WebSocket] },
     remoteAddress: '::ffff:192.168.2.133',
     checkIntervalTimer: null,
     upgradeTimeoutTimer: null,
     pingTimeoutTimer:
      Timeout {
        _called: false,
        _idleTimeout: 30000,
        _idlePrev: [TimersList],
        _idleNext: [Timeout],
        _idleStart: 137114,
        _onTimeout: [Function],
        _timerArgs: undefined,
        _repeat: null,
        _destroyed: false,
        [Symbol(unrefed)]: false,
        [Symbol(asyncId)]: 512,
        [Symbol(triggerId)]: 259 },
     transport:
      WebSocket {
        readyState: 'open',
        discarded: false,
        socket: [WebSocket],
        writable: true,
        perMessageDeflate: [Object],
        supportsBinary: true,
        _events: [Object],
        _eventsCount: 5,
        sid: 'xwVZDqAT2qorua6dAAAD',
        req: [IncomingMessage] },
     _events:
      [Object: null prototype] {
        close: [Array],
        data: [Function: bound ],
        error: [Function: bound ] },
     _eventsCount: 3 },
  rooms: { '1': '1', xwVZDqAT2qorua6dAAAD: 'xwVZDqAT2qorua6dAAAD' },
  acks: {},
  connected: true,
  disconnected: false,
  handshake:
   { headers:
      { origin: 'http://192.168.2.133:3000',
        upgrade: 'websocket',
        connection: 'Upgrade',
        'sec-websocket-key': 'RWvAUsJaWSDWvlEY3xAhKg==',
        'sec-websocket-version': '13',
        host: '192.168.2.133:3000',
        'accept-encoding': 'gzip',
        'user-agent': 'okhttp/3.12.1' },
     time: 'Wed Jun 12 2019 21:33:59 GMT-0700 (Pacific Daylight Time)',
     address: '::ffff:192.168.2.133',
     xdomain: true,
     secure: false,
     issued: 1560400439522,
     url: '/socket.io/?EIO=3&transport=websocket',
     query: { EIO: '3', transport: 'websocket' } },
  fns: [],
  flags: {},
  _rooms: [],
  my_id: 22,
  _events:
   [Object: null prototype] { 'event message': [Function], disconnect: [AsyncFunction] },
  _eventsCount: 2 }

2 个答案:

答案 0 :(得分:1)

通过查看socket.io网站,您可以做到:

io.on('connection', (socket) => {
     io.to(room).emit("event message", msg);
 }

答案 1 :(得分:1)

检查Socket.IO cheatsheet

io.on('connect', onConnect);

function onConnect(socket){

  // sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // sending to a specific room in a specific namespace, including sender
  io.of('myNamespace').to('room').emit('event', 'message');

  // sending to individual socketid (private message)
  io.to(`${socketId}`).emit('hey', 'I just met you');

  // WARNING: `socket.to(socket.id).emit()` will NOT work, as it will send to everyone in the room
  // named `socket.id` but the sender. Please use the classic `socket.emit()` instead.

  // sending with acknowledgement
  socket.emit('question', 'do you think so?', function (answer) {});

  // sending without compression
  socket.compress(false).emit('uncompressed', "that's rough");

  // sending a message that might be dropped if the client is not ready to receive messages
  socket.volatile.emit('maybe', 'do you really need it?');

  // specifying whether the data to send has binary data
  socket.binary(false).emit('what', 'I have no binaries!');

  // sending to all clients on this node (when using multiple nodes)
  io.local.emit('hi', 'my lovely babies');

  // sending to all connected clients
  io.emit('an event sent to all connected clients');

};