我写了一个向all个用户广播消息的代码:
// websocket and http servers
var webSocketServer = require('websocket').server;
...
...
var clients = [ ];
var server = http.createServer(function(request, response) {
// Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
...
});
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server.
httpServer: server
});
// This callback function is called every time someone
// tries to connect to the WebSocket server
wsServer.on('request', function(request) {
...
var connection = request.accept(null, request.origin);
var index = clients.push(connection) - 1;
...
请注意:
- 我没有任何用户参考,只有连接.
- 所有用户连接都存储在
array
中.
Goal:假设Node.js服务器想要向特定客户机(John)发送消息.NodeJS服务器如何知道John具有哪个连接?js服务器甚至不认识John.它所看到的都是联系.
所以,我认为现在,我不应该只通过连接来存储用户,相反,我需要存储一个对象,它将包含userId
和connection
对象.
Idea:个
-
页面加载完成后(DOM就绪)-建立到Node.js服务器的连接.
-
当Node.js服务器接受连接时-生成一个惟一的字符串并将其发送到客户端浏览器.将用户连接和唯一字符串存储在对象中.例如
{UserID:"6", value: {connectionObject}}
-
在客户端,当此消息到达时-将其存储在隐藏字段或Cookie中.(对于将来对NodeJS服务器的请求)
当服务器想要向John发送消息时:
-
在字典中找到john的用户ID,并通过相应的连接发送消息.
-
请注意没有asp.net服务器代码在此处(消息机制中)嵌入.只有点头*
Question:个
走这条路对吗?