Node js客户端未连接到运行在127.0.0.1:8080上的服务器

时间:2018-11-11 20:27:53

标签: node.js tcp server client

我正在尝试创建Node js TCP服务器和客户端。目前,我正在127.0.0.1:8080的IP地址上运行服务器。 我的客户正在尝试连接到该IP。我不知道为什么会失败,这是我的代码:

var net = require('net');
const readline = require('readline');

var clients = [];

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
});

function OpenServer() {
  var server = net.createServer(function(socket) {
    socket.write('Echo server\n');
    socket.name = socket.remoteAddress + ":" + socket.remotePort;
    socket.write(socket.name + " joined the chat\n");

    socket.on('data', function(data) {
      socket.write('socket Received: ' + data + '\n');
    });

    socket.on('connect', function(data){
      socket.write("new connection");
    });

    socket.pipe(socket);
  }).listen(8080, '127.0.0.1');
}

function OpenClient() {
  var client = new net.Socket();
  client.connect(8080, "127.0.0.1", function() {
    console.log('Connected');
  });

  client.on('data', function(data) {
    console.log('Client Received: ' + data + '\n');
    rl.question('How are you today? ', (answer) => {
      // TODO: Log the answer in a database
      client.write(`Thank you ${answer}`);
      rl.close();
    });
  });
  client.on('close', function() {
    console.log('Connection closed');
  });
}
OpenClient(); OpenServer();

这是我运行客户端时遇到的错误。

  

进程崩溃,错误:错误:连接ECONNREFUSED 127.0.0.1:8080   在TCPConnectWrap.afterConnect上[作为oncomplete](net.js:1174:14)

我也想说,我真的不知道IP 127.0.0.1是什么。 如果有人有更好的解决方案或更好的方法,我很乐意为您服务。

0 个答案:

没有答案