var net = require('net'); var server = net.createServer(function(socket){ socket .on('data',function(data){ console.log('socket data',data.toString()); socket.write( data.toString() ); }) .on('end',function(){ console.log('socket end') }) .on('error',function(error){ console.log('socket error',error); });}); server.listen(56200,function(){ console.log('server run at ',server.address());}); server.on('error',function(err){ throw err;});// 执行后:server run at { address: '::', family: 'IPv6', port: 56200 }
var net = require('net'); var client = net.createConnection({port:56200,host:'localhost'}); client.on('connect',function(){ console.log('client connect');}); client.on('data',function(data){ console.log('client data',toString());}); client.on('error',function(error){ throw error;}); client.on('close',function(){ console.log('client close');});
var net = require('net');var biz = require('./biz');var server = net.createServer(function(socket){ socket .on('data',function(data){ biz.do(data) .then(function(){ if( !socket.destroyed ) { socket.write( data.toString() ); } else { // do some report socket.destry(); } }) .catch(function(){ !socket.destroyed && socket.end('server handler error'); }); }) .on('end',function(){ console.log('socket end') }) .on('error',function(error){ console.log('socket error',error); });}); server.listen(56200,function(){ console.log('server run at ',server.address());});server.on('error',function(err){ throw err;});
var net = require('net');var MAX_REQUEST_BYTES = 2 * 1024 * 1024; // 2Mvar server = net.createServer(function(socket){ socket .on('data',function(data){ if(data.bytesRead > MAX_REQUEST_BYTES) { socket.pause(); socket.end('data is too big, forbidden'); // do some report } }) .on('end',function(){ console.log('socket end') }) .on('error',function(error){ console.log('socket error',error); });}); server.listen(56200,function(){ console.log('server run at ',server.address());}); server.on('error',function(err){ throw err;});
以上是Node.js中的網路通訊模組實作方法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!