我 4 小时前开始使用 Node.js,我不确定非阻塞功能。
我在 Node.JS 中编写了一个服务器,他需要通过 TCP 处理 C# 中的许多客户端,我不希望客户端在他从服务器得到答案之前等待 5 分钟。
我使用 2 个客户端尝试此代码,当使用第一个客户端时,我尝试发送一个大文件(以查看第二个是否可以执行某些请求),第二个尝试连接并且只收到 ID 表示在 transfert 后建立了连接(实际上是在 Visual Studio 崩溃之后,因为我的 C# 客户端无法发送大文件而不在 30 秒后崩溃......)
我尝试使用 sleep.sleep(5000) 进行测试,但他跳跃悬停,所以我不知道如何测试它是否阻塞以及如何使其不阻塞
感谢并为我糟糕的英语感到抱歉,我会说法语
这是我的服务器:
net = require('net');
fs = require('fs');
mysql = require('mysql');
var client = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '*****',
database : 'test',
});
var clients = [];
function clientStruct()
{
this.id;
this.soc;
this.lastCommand;
}
var id = 0;
//?? Difference between Server and createServer
var s = net.createServer(function(socket) {
var client = new clientStruct();
client.id = id++;
client.soc = socket;
clients.push(client);
var stream = null;
socket.write(client.id + '\n');
socket.on('data', function(msg_sent)
{
var msg = msg_sent.toString().split(' ');
if (msg[0] == '-command')
{
client.lastCommand = null;
}
if (client.lastCommand == 'modifyProfilePic')
{
stream.write(msg_sent);
client.lastCommand = 'writeFile';
socket.write('0\n');
console.log('WRITE THE FILE');
sleep.sleep(5000);
console.log('sleep for 5 sec');
}
else if (client.lastCommand == 'writeFile')
{
if (msg_sent == '\n')
console.log('END');
else
stream.write(msg_sent);
//console.log(msg_sent.toString());
}
//FIRST ARGUMENTS
else if (msg[1] == 'mkuser')
{
socket.write('0\n');
client.lastCommand = msg[1];
}
else if (msg[1] == 'modifyProfilePic')
{
stream = fs.createWriteStream('test2.mp4', { flags : 'w' });
socket.write('0\n');
client.lastCommand = msg[1];
}
else
{
socket.write('1\n');
console.log('error');
client.lastCommand = null;
}
});
socket.on('end', function() {
var i = clients.indexOf(socket);
console.log('END of client ' + client.id + ' index ' + i + ' tab size ' + clients.length);
clients.splice(i, 1);
});
socket.on('error', function() {
var i = clients.indexOf(socket);
console.log('ERROR of client ' + client.id + ' index ' + i + ' tab size ' + clients.length);
clients.splice(i, 1);
});
});
var PORT = 10001
s.listen(PORT);
console.log('System waiting at localhost port:' + PORT)