简体   繁体   English

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

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

I'm trying to test out Node.js and I'm using this code: 我正在尝试测试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.");

To send a byte array to any connections that show up on port 7000 of local host. 将字节数组发送到本地主机端口7000上显示的任何连接。 Nothing is connecting though, I've tried firefox (localhost:7000, and 127.0.0.1:7000) I tried PuTTy, and even writing my own Java TCP Client to connect to local host, but nothing is working, so I'm convinced that the code is wrong. 没有什么是连接的,我尝试过firefox(localhost:7000和127.0.0.1:7000)我试过PuTTy,甚至编写自己的Java TCP Client连接到本地主机,但没有任何工作,所以我深信不疑代码错了。

Can someone please tell me why my code won't allow connections? 有人可以告诉我为什么我的代码不允许连接?

You seem to be overcomplicating the connection part. 您似乎过度复杂的连接部分。 The callback with the socket is already the connection event so you don't need to listen to it separately. 使用套接字的回调已经是连接事件,因此您无需单独收听它。 Also, if you want to send binary, use the Buffer class. 此外,如果要发送二进制文件,请使用Buffer类。 Here's your code changed. 这是你的代码改变了。 Remember to set your mode to telnet in putty when connecting. 记得在连接时将模式设置为putty中的telnet。 I've also changed the end() to write() so it doesn't auto close the connection. 我还将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.");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM