0

我正在尝试像 telnet 连接一样在套接字上使用 REPL,但是当我按 CTRL + C 或 CTRL + D 或产生错误时,套接字连接挂起并且不响应任何内容。

node.js 代码是:

var net = require("net");
var connections = 0;

// Socket port 5001
net.createServer(function (socket) {
  connections += 1;
  var server = require("repl").start(
      'session:' + connections + ' > ', 
      socket
  );
  server.rli.on('exit', function() {
    socket.end();
  });
}).listen(5001);

// Console
var server = require("repl").start('session:' + (++connections) + ' > ', null);

并从其他终端运行:

telnet localhost 5001

问题是什么?

4

1 回答 1

0

也许是linux的问题。

我尝试了一个带有 node 的 Telnet 服务器示例。当我在窗口上运行时,我按下的每个键都由receiveData函数处理,但在 linux 中没有。在linux中,每行处理一行,而不是每个字符一个字符。

这是我探测过的代码:

var net = require('net');
var sockets = [];

/*
 * Cleans the input of carriage return, newline
 */
function cleanInput(data) {
    return data.toString().replace(/(\r\n|\n|\r)/gm,"");
}

/*
 * Method executed when data is received from a socket
 */
function receiveData(socket, data) {
    var cleanData = cleanInput(data);
    if(cleanData === "@quit") {
        socket.end('Goodbye!\n');
    }
    else {
        for(var i = 0; i<sockets.length; i++) {
            if (sockets[i] !== socket) {
                sockets[i].write(data);
            }
        }
    }
    socket.write('Data: ' + data);
}

/*
 * Method executed when a socket ends
 */
function closeSocket(socket) {
    var i = sockets.indexOf(socket);
    if (i != -1) {
        sockets.splice(i, 1);
    }
}

/*
 * Callback method executed when a new TCP socket is opened.
 */
function newSocket(socket) {
    sockets.push(socket);
    socket.write('Welcome to the Telnet server!\n');
    socket.on('data', function(data) {
        receiveData(socket, data);
    })
    socket.on('end', function() {
        closeSocket(socket);
    })
}

// Create a new server and provide a callback for when a connection occurs
var server = net.createServer(newSocket);

// Listen on port 8888
server.listen(8888);
于 2013-01-20T09:56:02.230 回答