在Socket IO中向特定客户端发送消息

22 sockets node.js

我正在使用Socket IO v1.4.5并尝试了3种不同的方式,但没有任何结果.

client.emit('test', 'hahahaha');
io.sockets.socket(id).emit('test',''hahaha); 
io.sockets.connected[id].emit('test','hahaha');
Run Code Online (Sandbox Code Playgroud)

这是我的服务器端

var socket = require( 'socket.io' );
var express = require( 'express' );
var http = require( 'http' );
var dateFormat = require('date-format');
var app = express();
var server = http.createServer( app );
var io = socket.listen( server );
io.sockets.on( 'connection', function( client ) {
    user[client.id]=client;

//when we receive message 
    client.on('message', function( data ) {
        console.log( 'Message received from' + data.name + ":" + data.message +' avatar' +data.avatar );
        client.emit('test', 'hahahaha');
});
Run Code Online (Sandbox Code Playgroud)

任何帮助都会很棒.感谢您的帮助.Kind Regard

Dat*_*sik 103

要向特定客户端发送消息,您需要这样做:

socket.broadcast.to(socketid).emit('message', 'for your eyes only');
Run Code Online (Sandbox Code Playgroud)

这是一个很好的插座小骗子:

 // sending to sender-client only
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.emit('message', "this is a test");

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');

 // sending to all clients in 'game' room(channel), include sender
 io.in('game').emit('message', 'cool game');

 // sending to sender client, only if they are in 'game' room(channel)
 socket.to('game').emit('message', 'enjoy the game');

 // sending to all clients in namespace 'myNamespace', include sender
 io.of('myNamespace').emit('message', 'gg');

 // sending to individual socketid
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');
Run Code Online (Sandbox Code Playgroud)

感谢/sf/answers/706952781/


最简单的方法,而不是直接发送到套接字,将为2个用户创建一个空间,并在那里自由发送消息.

socket.join('some-unique-room-name'); // Do this for both users you want to chat with each other
socket.broadcast.to('the-unique-room-name').emit('message', 'blah'); // Send a message to the chat room.
Run Code Online (Sandbox Code Playgroud)

否则,您将需要跟踪每个单独的客户端套接字连接,并且当您想要聊天时,您将必须查找该套接字连接并使用我上面提到的功能专门发送到该套接字连接.房间可能更容易.

  • **请注意**:如果使用`socket.broadcast.to(id)`的套接字是自己的(因此,`socket.id == id`),那么这将不起作用.相反,使用`io.sockets.to(id).emit('event-name-message','这只适合你')`. (3认同)