服务器端:
var net = require('net');
var server = net.createServer();
server.on('close', function(){
console.log('__server close');
});
server.on('connection', function(socket){
console.log('__server connection')
socket.on('data',function(data){
console.log('__server receive data');
console.log(data.toString());
if(data.toString() === 'i am client'){
socket.write('i am server, i receive you message');
}
})
socket.on('error',function(error){
console.error(error);
})
})
server.on('error',function(error){
console.error(error);
})
server.listen(4000, function(){
console.log('server listen at 4000');
});
客户端:
var net = require('net');
var client = new net.Socket();
client.connect(4000, '127.0.0.1',function(){
console.log('CONNECTED TO');
client.write('i am client');
})
client.on('data',function(data){
console.log('__client receive data');
console.log(data.toString());
})