为什么不是我的hello world node.js tcp服务器获取任何连接?

时间:2014-04-26 23:46:35

标签: javascript node.js tcp

我试图测试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 Client连接到本地主机,但没有任何工作,所以我&# 39; m确信代码是错误的。

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

1 个答案:

答案 0 :(得分:2)

您似乎过度复杂了连接部分。使用套接字的回调已经是连接事件,因此您不需要单独收听它。此外,如果要发送二进制文件,请使用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.");