Client.js:
1 var net=require(‘net‘);
2
var client=net.connect({port:8124,host:‘127.0.0.1‘},function(){
3
console.log(‘Success‘);
4
client.write(‘world‘);
5
6
});
7
//客户端接收数据
8
client.on(‘data‘,function(data){
9
console.log(data.toString());
10
client.end();//只要客户端接收到数据,就立刻关闭连接
11
});
12
//客户端断开连接
13
client.on(‘end‘,function(){
14
console.log(‘disconnected from server‘);
15
});
~
server.js:
1
var net=require(‘net‘);
2
var server=net.createServer(function(c){
3
console.log(‘client connected‘);
4
c.on(‘end‘,function(){
5
console.log(‘client disconnected‘);
6
});
7
c.on(‘data‘,function(data){
8
console.log(data.toString);
9
});
10
c.write(‘hello‘);
11
c.pipe(c);
12
});
13
14
server.listen(8124,function(){
15
console.log(‘server bound‘);
16
});