2016-02-28 156 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"); 
    } 
相關問題