簡體   English   中英

為什么不是我的hello world node.js tcp服務器獲取任何連接?

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

我正在嘗試測試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連接到本地主機,但沒有任何工作,所以我深信不疑代碼錯了。

有人可以告訴我為什么我的代碼不允許連接?

您似乎過度復雜的連接部分。 使用套接字的回調已經是連接事件,因此您無需單獨收聽它。 此外,如果要發送二進制文件,請使用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.");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM