我需要一个套接字服务器,它必须从服务器上不同端口的100个客户端接收数据。我已经创建了一组服务器套接字,我不知道这是否正确。
当我有大约100个客户端发送数据时,我还发现接收数据的速度很慢,并且由于某种原因,服务器停止从10个客户端接收数据。
以下是我的3端口代码。
var net = require('net');
var rl = require('readline');
var fs = require('fs');
var ports = [60001, 60002, 60003];
var server = new Array();
ports.forEach(function(value) {
server[value] = net.createServer(function (socket) { // array of socket servers
socket.on('error', function(err) {
console.log(err.stack);
server[value].close();
server[value].listen(value); //start listen again
});
socket.on('end', function() {
console.log('client disconnected: ' + value);
server[value].close();
server[value].listen(value); //start listen again
});
console.log('client connected: ' + value);
var intf = rl.createInterface(socket, socket);
intf.on('line', function (line) {
fs.exists(__dirname + "\\file" + value.toString() + ".txt", function (exists) {
if(exists){
var stream = fs.createWriteStream(__dirname + "\\file" + value.toString() + ".txt", {'flags': 'a'});
} else {
var stream = fs.createWriteStream(__dirname + "\\file" + value.toString() + ".txt", {'flags': 'w'});
}
try {
stream.once('open', function(fd) {
console.log(value.toString() + " - " + line);
stream.write(line + "\r\n");
stream.end();
});
} catch (x) {
console.log(x.stack);
}
});
});
});
server[value].listen(value); // listen many ports
});