为什么不是'我的helloworld node.js tcp服务器没有连接

Why isn't my hello world node.js tcp server getting any connections?

本文关键字:tcp js 服务器 连接 node helloworld 我的 为什么不      更新时间:2023-09-26

我正在尝试测试Node.js,我使用的代码是:

// Load the net, and sys modules to create a tcp server.
var net = require('net');
var sys = require('sys');
// Setup a tcp server
var server = net.createServer(function (socket) {
  // Every time someone connects, tell them hello and then close the connection.
  socket.addListener("connect", function () {
    //sys.puts("Connection from " + socket.remoteAddress);
    console.log("Person connected.");
    var myPacket = [1,2,3,4,5];
    sys.puts(myPacket);
    socket.end("Hello World'n");
  });
});
// Fire up the server bound to port 7000 on localhost
server.listen(7000, "localhost");
// Put a friendly message on the terminal
console.log("TCP server listening on port 7000 at localhost.");

将字节数组发送到本地主机端口7000上显示的任何连接。虽然没有任何连接,但我尝试过firefox(localhost:7000和127.0.0.1:7000),我尝试过PuTTy,甚至编写了自己的Java TCP客户端来连接到本地主机,但没有任何工作,所以我确信代码是错误的。

有人能告诉我为什么我的代码不允许连接吗?

您似乎过于复杂化了连接部分。带有套接字的回调已经是连接事件,因此不需要单独侦听它。此外,如果要发送二进制文件,请使用Buffer类。这是您更改的代码。连接时请记住将您的模式设置为putty中的telnet。我还将end()更改为write(),这样它就不会自动关闭连接。

// Load the net, and sys modules to create a tcp server.
var net = require('net');
var sys = require('sys');
// Setup a tcp server
var server = net.createServer(function (socket) {
    //sys.puts("Connection from " + socket.remoteAddress);
    console.log("Person connected.");
    var myPacket = new Buffer([65,66,67,68]);
    socket.write(myPacket);
    socket.write("Hello World'n");
});
// Fire up the server bound to port 7000 on localhost
server.listen(7000, "localhost");
// Put a friendly message on the terminal
console.log("TCP server listening on port 7000 at localhost.");