我有一个以下NodeJS
服务器文件应该处理以下JSON
消息:
message
作为密钥,请发送一些回复。app
作为密钥,请向客户端发送一些DLL
。现在我有兴趣处理多个客户端,在这种情况下,只会在JSON中发送Key
消息。
以下是代码:
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。
答案 0 :(得分:0)