Node.js:如何在单个端口上监听通信和响应

时间:2014-11-30 18:37:54

标签: javascript node.js sockets port

我目前正在为Node.js中的PHP构建一个远程调试客户端。 XDebug是一个允许远程调试的PHP库,它通过localhost上的端口9000发送消息,因此远程调试客户端可以监听消息并在同一主机和端口上进行响应。

所以,我做了一个TCP服务器,它监听端口9000,并在解析数据后,做出相应的响应:

var net = require('net');
var transactionID = 1234;
var parseXMLString = require('xml2js').parseString;

/**
 * Create a server to respond to the debugger engine.
 *
 * @param  {Socket} connection
 */
var server = net.createServer(function(socket) { //'connection' listener
  console.log('socket connected to server');
  socket.on('end', function() {
    console.log('socket disconnected to server');
  });
  /**
   * When the debugger engine sends a message over port 9000,
   * send a response.
   *
   * @param  {Buffer} data
   */
  socket.on('data', function(data) {
    // Data comes through as a buffer, stringify it.
    var dataStringified = data.toString(),
      splitData = null,
      xmlStatement = null,
      dataLength = null;
    // Data comes through as a string separated by a null byte, so split it up.
    splitData = dataStringified.split('\u0000');
    dataLength = splitData[0];
    xmlStatement = splitData[1];
    parseXMLString( xmlStatement, function( err, result ) {
      if ( 'init' in result ) {
        var command = 'run -i 1234';
        socket.write( command );
      }
    });
  });
  // socket.pipe(socket);
});

/**
 * Listen to port 9000 to create connections from the debugger engine to the server.
 */
server.listen(9000, function() { //'listening' listener
  console.log('server listening on port 9000');
});

但是,未写入套接字/端口。

我见过其他服务器示例中使用的socket.pipe(socket)。如果代码中的那一行未注释,则端口会被写入,但是,它会建立一个循环连接,并且从XDebug发送的任何消息都会被发送回自身。

我错过了什么?

0 个答案:

没有答案