2016-02-28 102 views
12

我正在使用Socket IO v1.4.5并尝试了以下3种不同的方式,但没有任何结果。将消息发送到Socket IO中的特定客户端

client.emit('test', 'hahahaha'); 
io.sockets.socket(id).emit('test',''hahaha); 
io.sockets.connected[id].emit('test','hahaha'); 

这里是我的服务器端

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'); 
}); 
为help.Kind方面

任何帮助将是great.Thanks

回答

70

要发送一个消息,你需要做的是,像这样一个特定的客户端:

socket.broadcast.to(socketid).emit('message', 'for your eyes only'); 

这里是插座一个可爱的小小抄:

// 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'); 

感谢https://stackoverflow.com/a/10099325


最简单的方法,而不是直接发送到插座,将创建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. 

否则,你将需要跟踪每个个人客户套接字连接的,当你想要聊天你要查找该插座连接,并使用功能专门发出到一个我上面说过。房间可能更容易。

+0

Hi.So我只需要该行添加到服务器的网站?还有什么别的看起来不错? –

+1

@HoàngPhúcVũ我不是100%确定你要在你的代码中完成什么,你说你想发送到一个特定的套接字连接,但我没有看到试图找到一个套接字ID并发送给他们。 – Datsik

+0

我想要的是发送2个用户之间的私人消息。所以你有任何关于这种情况下的建议。感谢您的帮助 –

0

Socket.io版本2.0.3+

一封邮件发送给特定的插座

let namespace = null; 
    let ns = _io.of(namespace || "/"); 
    let socket = ns.connected[socketId] // assuming you have id of the socket 
    if (socket) { 
     console.log("Socket Connected, sent through socket"); 
     socket.emit("chatMessage", data); 
    } else { 
     console.log("Socket not connected, sending through push notification"); 
    } 
相关问题