我正在尝试管理一堆套接字连接。我的应用程序基本上是一个 http 服务器,它接收帖子并将其传递到套接字。当客户端打开套接字连接时,它们会发送带有 id 的连接消息:
{"m":"connect","id":"1"}
然后应用程序将此 ID 和套接字保存在 id2socket 和 socket2id 映射中。断开连接时,套接字/id 对将从映射中删除。
帖子还将包含一个 id,这表明帖子数据应发送到具有该 id 的套接字。
这太棒了,这对于单个打开的套接字来说效果很好。然而,当我打开多个套接字,然后关闭一个套接字时,断开连接会删除 map 上的所有内容。我认为我对 Node 中套接字的理解不完整 - 回调中是否仅使用一个套接字对象?有没有更好的方法来管理我的开放套接字连接和 ID?
启动服务器:
>>node server.js
TCP server listening on 127.0.0.1:5280
HTTP server listening on 127.0.0.1:9002
远程登录:
>>telnet localhost 5280
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
{"m":"connect","id":"123"}
{"m":"connect","id":"123","success":"true"}
连接后的服务器:
>>Connection from 127.0.0.1:57572
received data: {"m":"connect","id":"123"}
id: 1
m: connect
associating uid 1 with socket [object Object]
发表帖子:
python post.py {"foo":"bar"}
因此,这对于多个打开的套接字来说效果很好(只要 1 个设备的 ID 为 123,服务器目前已将其硬连线)。但是,一旦关闭一个连接,所有套接字连接都会从映射中删除。
这是我的代码:
用于发布的 python 脚本:
import sys
import json
import httplib, urllib, urllib2
values = json.loads('{"foo":"bar"}')
headers = {"Content-type": "application/json"}
conn = httplib.HTTPConnection('127.0.0.1', 9002)
headers = {"Content-type": "application/json"}
conn.request("POST", "", json.dumps(values), headers)
response = conn.getresponse()
print "response.status: "+response.status
print "response.reason: "+response.reason
print "response.read: "+response.read()
conn.close()
Node 服务器(http 和 tcp),通过硬连线将数据发送到 post 设备“123”:
var net = require('net'); // tcp-server
var http = require("http"); // http-server
var qs = require('querystring'); // http-post
// Map of sockets to devices
var id2socket = new Object;
var socket2id = new Object;
// Setup a tcp server
var server_plug = net.createServer(function(socket) {
// Event handlers
socket.addListener("connect", function(conn) {
console.log("Connection from " + socket.remoteAddress + ":" + socket.remotePort );
});
socket.addListener("data", function(data) {
console.log("received data: " + data);
try {
request = JSON.parse(data);
response = request;
if(request.m !== undefined && request['id'] !== undefined){ // hack on 'id', id is js obj property
console.log("id: "+request['id']);
console.log("m: "+request.m);
if(request.m == 'connect'){
console.log("associating uid " + request['id'] + " with socket " + socket);
id2socket[request['id']] = socket;
socket2id[socket] = request['id'];
response.success = 'true';
} else {
response.success = 'true';
}
}
socket.write(JSON.stringify(response));
} catch (SyntaxError) {
console.log('Invalid JSON:' + data);
socket.write('{"success":"false","response":"invalid JSON"}');
}
});
socket.on('end', function() {
id = socket2id[socket]
console.log("socket disconnect by id " + id);
// wipe out the stored info
console.log("removing from map socket:"+socket+" id:"+id);
delete id2socket[id];
delete socket2id[socket];
});
socket.on('timeout', function() {
console.log('socket timeout');
});
});
// Setup http server
var server_http = http.createServer(
// Function to handle http:post requests, need two parts to it
// http://jnjnjn.com/113/node-js-for-noobs-grabbing-post-content/
function onRequest(request, response) {
request.setEncoding("utf8");
request.addListener("data", function(chunk) {
request.content += chunk;
});
request.addListener("end", function() {
console.log("post received!");
//console.log("Request received: "+request.content);
if (request.method == 'POST') {
//var json = qs.parse(request.content);
//console.log("Post: "+json);
// HACK TO TEST STUFF:
// send a message to one of the open sockets
try {
var socket = id2socket['123']; //hardwired
socket.write('{"m":"post"}');
} catch (Error) {
console.log("Cannot find socket with id "+'123');
}
}
});
}
);
// Fire up the servers
var HOST = '127.0.0.1';
var PORT = 5280;
var PORT2 = 9002;
server_plug.listen(PORT, HOST);
console.log("TCP server listening on "+HOST+":"+PORT);
server_http.listen(PORT2);
console.log("HTTP server listening on "+HOST+":"+PORT2);
最佳答案
对象仅将字符串作为其属性的键。正如您的日志所示,套接字对象被转换为字符串 "[object Object]"
。结果,套接字 #2 覆盖了对象中套接字 #1 的 id,因为所有套接字都被转换为相同的字符串键。因此,对象中始终只有一个属性,因为所有套接字都归结为同一个键。当您尝试删除套接字 #2 的 id 时,单个属性将被删除并且对象为空。
当用作键时,您似乎希望为每个单独的套接字提供一个自定义属性。您可以使用 WeakMap
来实现此目的。 WeakMap
确实允许对象作为键(而不是仅字符串键),但由于它们相对较新,目前可能包含错误。
(请注意,id2socket
映射可以只是一个普通对象,因为数字可以很好地转换为字符串,并且每个数字都有自己不同的字符串表示形式* .)
使用WeakMap
如下:
var socket2id = new WeakMap; // as if you were doing: var socket2id = {};
socket2id.set(socket, id); // as if you were doing: socket2id[socket] = id;
socket2id.get(socket); // as if you were doing: socket2id[socket];
socket2id.delete(socket); // as if you were doing: delete socket2id[socket];
确保使用 node --harmony
(>= 0.7) 或 node --harmony_weakmaps
(<= 0.6) 运行。
* 0
和 -0
是异常(exception),但无论如何您都不应该使用 -0
因为0 === -0
,因此很难区分它们。
关于javascript - 在 Node.js 中创建 id 到套接字的映射,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9232108/