我有下面的NodeJS服务器文件,它应该处理以下JSON消息:
message作为密钥,发送一些响应。app作为密钥,则向客户端发送一些DLL。现在,我感兴趣的是处理多个客户机,在本例中,这些客户机将只以Key的形式在JSON中发送消息。
以下是代码:
var net = require('net');
var fs = require('fs');
var util = require('util');
var server = net.createServer(function(c) { //'connection' listener
console.log('client connected');
c.on('end', function() {
console.log('client disconnected');
});
c.on('data', function(data) {
var json = JSON.parse(data.toString());
if(json.heartbeat){
if(json.first_fetch === "1"){
c.write("{\"config_changed\":\"true\",\"config\":\"This is some config\"}"); // JSON Message here
}
else{
c.write("{\"config_changed\":\"false\"}");
}
}
else if(json.message){
c.write("{\"success\":\"true\"}");
}
else if(json.app){
fs.exists('apps/'+ json.app + ".dll", function (exists) {
util.debug(exists ? "it's there" : "Its not there");
});
var stats = fs.statSync('apps/'+ json.app + ".dll")
var fileSizeInBytes = stats["size"]
var message = json.app + "\n" + fileSizeInBytes + "\n";
c.write(message);
fs.open('apps/'+ json.app + ".dll","r", function(status, fd){
console.log(fd);
var read_bytes = 0;
var fileStream = fs.createReadStream('apps/'+ json.app + ".dll");
fileStream.on('data',function(chunk){
c.write(chunk);
});
})
}
else
{
c.write("{\"some\":\"error\"}");
}
});
c.on('error', function (e) {
console.log(e);
});
// c.pipe(c);
});
server.listen(1936, function() { //'listening' listener
console.log('server bound');
});我的客户端将以{"message":"This is message"}的形式发送消息,服务器将发送{"success":"true"}。我收到了我创建的服务器的以下基准测试:
当每个客户端向一台服务器发送消息时,它们的时间会大大减少。我试图一次运行多台服务器,但它提供了:
events.js:85
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at exports._errnoException (util.js:746:11)
at Server._listen2 (net.js:1156:14)
at listen (net.js:1182:10)
at Server.listen (net.js:1267:5)
at Object.<anonymous> (C:\Users\Dell\Desktop\nodeserver\server.js:54:8)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)如果我想获得每个客户端的200K in 7 seconds性能,我应该如何进行。我想运行多个服务器实例,使用负载均衡器来提高服务器效率。我在使用Windows。
发布于 2015-09-01 11:12:12
尝试将node.js集群模块用于此https://nodejs.org/api/cluster.html
不同的nodejs实例不能共享同一个端口
另一种方法是使用外部负载均衡器,例如nginx。
balancing.html
https://stackoverflow.com/questions/32329201
复制相似问题