在Node.js WebSocket服務器中,由於您正在對服務器進行編碼,因此您可以完全控制誰獲得了什麼消息。你可以做這樣的事情...
當客戶端與服務器建立WebSocket連接並將其連接對象存儲在一個數組中時,可以將其連接的索引視爲其ID。如果你願意,你可以把這個ID(和他們的IP地址)廣播給那個地方的所有其他客戶,讓他們知道誰已經連接。然後,當客戶想要發送消息到另一個客戶端或客戶端時,讓客戶端進行消息傳遞包括目標客戶端和消息。這裏是服務器的相關部分:
var client_list = [];
ws_server.on('request', function(request) {
var connection = request.accept(null, request.origin);
//let all other clients know that a new client has arrived
//send the new client's ID and IP address
for(var i = 0; i < client_list.length; i++) {
client_list[i].send(JSON.stringify({
type: "new client",
data: {
ID: client_list.length,
IP: connection.remoteAddress
}
}));
}
//store the new connection
client_list.push(connection);
//let the new client know what their ID is
connection.send(JSON.stringify({
type: "assignment",
data: {
ID: client_list.length - 1
}
}));
//when you receive a message from a client of type "relay",
//send it to the intended targets
connection.on("message", function(message) {
var parsed_message = JSON.parse(message.utf8Data);
if(parsed_message.type === "relay") {
for(var i = 0; i < parsed_message.targets.length; i++) {
client_list[parsed_message.targets[i]].send(parsed_message.data);
}
}
});
});
從客戶端傳出的消息是這樣的:
{
type: "relay",
targets: [1, 33, 7],
data: {
content: "Hey guy!",
origin: my_id
}
}
我沒有測試,所以讓我知道,如果它給你帶來麻煩。
讓我知道如果您有任何後續問題,如果我的代碼被破壞。 – Jason
我會做傑森,我還沒有時間檢查它,但我會盡快發表評論,只要我實施您的解決方案,謝謝,但它看起來像我正在尋找..! –