我有一个问题,就“IF”条件而言,我需要发送消息“socket.write('11')”,但如果第二个“socket.write”未打开,它不会发送消息编码。在我的代码上,我不需要第二次写入。为什么会这样?
** 我发现了其他错误,如果我没有将 var“数据”放在 socket.write() 上,它不会向客户端发送任何消息。
问候
var net = require('net');
var HOST = '192.168.0.104';
var PORT = 6060;
var connections = 0;
var clients = [];
net.createServer(function (socket) {
// Identify this client
socket.name = socket.remoteAddress + ":" + socket.remotePort
// Put this new client in the list
clients.push(socket);
// Send a nice welcome message and announce
socket.write("Welcome Client: " + socket.name + "\n");
connections++;
console.log('Active connections: ' + connections);
console.log(socket.name + " joined the chat.");
// Handle incoming messages from clients.
socket.on('data', function (data) {
var response = data.toString();
var recv = response.length;
if (recv == 16){
socket.write('11'); //****** First write
console.log("11");
}
console.log(socket.name + "length: " + recv);
socket.write('You said: "' + data); //***** Second write
});
// Remove the client from the list when it leaves
socket.on('end', function () {
clients.splice(clients.indexOf(socket), 1);
console.log(socket.name + " left the chat.");
connections--;
console.log('Active connections: ' + connections);
});
}).listen(PORT, HOST);
// Put a friendly message on the terminal of the server.
console.log('Server listening on ' + HOST +':'+ PORT);