官方API文档地址:https://nodejs.org/api/net.html
- 创建一个server.js
1 var net = require('net'); 2 var PORT = 8099; 3 var HOST = '127.0.0.1' 4 5 var server = net.createServer(); 6 server.on('connection', function(client) { 7 client.name = client.remoteAddress + ':' + client.remotePort 8 client.write('Hi ' + client.name + '! '); 9 10 client.on('data', function(data) { 11 client.write(data); 12 }) 13 client.on('end', function() { 14 client.write('Bye ' + client.name + '! '); 15 }) 16 17 client.on('error', function(e) { 18 console.log('error:'+ e.message); 19 }) 20 }); 21 22 server.on('listening', function() { 23 console.log('Server is listening on port', PORT); 24 }); 25 server.listen(PORT,HOST);
- 连接