问题描述
我正在尝试在 node.js 中使用套接字,我成功了,但我不知道如何在我的代码中区分客户端.关于套接字的部分是这样的:
I am trying to use sockets with node.js, I succeded but I don't know how to differentiate clients in my code.The part concerning sockets is this:
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 8080});
wss.on('connection', function(ws) {
ws.on('message', function(message) {
console.log('received: %s', message);
ws.send(message);
});
ws.send('something');
});
此代码适用于我的客户端 js.
This code works fine with my client js.
但我想向特定用户或所有在我的服务器上打开套接字的用户发送消息.
But I would like to send a message to a particular user or all users having sockets open on my server.
在我的例子中,我以客户端的身份发送了一条消息,我收到了回复,但其他用户什么也没显示.
In my case I send a message as a client and I receive a response but the others user show nothing.
例如,我希望 user1 通过 webSocket 向服务器发送消息,然后向打开套接字的 user2 发送通知.
I would like for example user1 sends a message to the server via webSocket and I send a notification to user2 who has his socket open.
推荐答案
您可以简单地将用户 ID 分配给一个数组 CLIENTS[],这将包含所有用户.您可以直接向所有用户发送消息,如下所示:
You can simply assign users ID to an array CLIENTS[], this will contain all users. You can directly send message to all users as given below:
var WebSocketServer = require('ws').Server,
wss = new WebSocketServer({port: 8080}),
CLIENTS=[];
wss.on('connection', function(ws) {
CLIENTS.push(ws);
ws.on('message', function(message) {
console.log('received: %s', message);
sendAll(message);
});
ws.send("NEW USER JOINED");
});
function sendAll (message) {
for (var i=0; i<CLIENTS.length; i++) {
CLIENTS[i].send("Message: " + message);
}
}
这篇关于webSocketServer node.js 如何区分客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!