我是 nodejs 的新手,我需要构建一个正常运行时间监控系统,使用 TCP 服务器和客户端以及保持连接。目前我尝试构建该系统的基础,但服务器不显示来自客户端的任何消息。知道我哪里做错了吗?
服务器:
var net = require('net');
var server = net.createServer(function (conn)
{
conn.write('Hello here server');
}
).listen(1234);
server.on('data', function (data)
{
console.log('client: ' + data);
});
客户:
var net = require('net');
var client = net.connect({port: 1234}, function(){
console.log('client connect');
});
client.setEncoding('utf8');
client.write('hello here client');
client.on('data', function (data)
{
console.log('server: ' + data);
});
知道为什么服务器没有得到客户端发送的消息的任何输出吗?正如你所看到的,它几乎和聊天一样,但我最后需要使用 keep-alive,connection。
最佳答案
更改您的服务器以监听 createServer
中的数据:
var net = require('net');
var server = net.createServer(function (conn) {
conn.write('Hello here server');
conn.on('data', function (data) {
console.log('client: ' + data);
});
}
).listen(1234);
关于node.js - nodejs 简单的 TCP 聊天,服务器没有收到客户端消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676931/