📜  nodejs tcp 客户端 - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:04:18.188000             🧑  作者: Mango

代码示例2
var net = require('net');

var server = net.createServer();    
server.on('connection', handleConnection);
server.listen(9000, function() {    
  console.log('server listening to %j', server.address());  
});
function handleConnection(conn) {    
  var remoteAddress = conn.remoteAddress + ':' + conn.remotePort;  
  console.log('new client connection from %s', remoteAddress);
  conn.on('data', onConnData);  
  conn.once('close', onConnClose);  
  conn.on('error', onConnError);
  function onConnData(d) {  
    console.log('connection data from %s: %j', remoteAddress, d);  
    conn.write(d);  
  }
  function onConnClose() {  
    console.log('connection from %s closed', remoteAddress);  
  }
  function onConnError(err) {  
    console.log('Connection %s error: %s', remoteAddress, err.message);  
  }  
}