[英]How to distinguish web sockets on server
I am trying to create a server with clients. 我正在尝试使用客户端创建服务器。 Each client has a websocket and a web worker, and each worker has an own websocket to the server.
每个客户端都有一个websocket和一个Web工作程序,每个工作人员都有一个到服务器的自己的Websocket。 The problem is, that i have a place on the server, where i am storing all connections
问题是,我在服务器上有一个地方,用于存储所有连接
wss.on('connection', function connection(ws) { var cid = "" + ++cid_counter; server.users[cid] = ws; ... }
But now they are all storing in server.users[], and i want to store clients sockets in server.users and worker sockets in server.wokers[], but i have no idea, how to distinguish there two different types of web sockets. 但是现在它们都存储在server.users []中,我想将客户端套接字存储在server.users中,将工作程序套接字存储在server.wokers []中,但是我不知道如何区分两种不同的Web套接字。 Maybe i could send a message, when creating a new web socket or any other solutions?
创建新的Web套接字或任何其他解决方案时,也许可以发送消息?
Thanks in forward 谢谢前进
You should add auth to your sockets so you can identify the client. 您应该将auth添加到套接字中,以便可以标识客户端。
Refer to this: socketio-auth 参考此: socketio-auth
You can issue unique keys to clients and workers or whoever you want and then require them to emit to "authenticate" event. 您可以向客户和工作人员或任何您想要的人发出唯一的密钥,然后要求它们发出“身份验证”事件。
You can distinguish them by having a key "type" in the db. 您可以通过在数据库中使用键“类型”来区分它们。
From npm: 从npm:
Client : 客户 :
var socket = io.connect('http://localhost');
socket.on('connect', function(){
socket.emit('authentication', {username: "John", password: "secret"});
socket.on('authenticated', function() {
// use the socket as usual
});
});
Server : 服务器 :
var io = require('socket.io').listen(app);
require('socketio-auth')(io, {
authenticate: function (socket, data, callback) {
//get credentials sent by the client
var key = data.key;
db.findUser('Users', {secret: key}, function(err, user) {
//inform the callback of auth success/failure
if (err || !user) return callback(new Error("User not found"));
return callback(null, user);
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.