1. TCP和UDP
1.1 TCP服务端
var net = require('net');
var server = net.createServer();
server.on('connection',function(socket){
socket.setEncoding('utf8');
socket.on('data',function(data){
console.log(data.toString());
});
socket.on('end',function(){
console.log('end');
});
});
server.listen(8765,'127.0.0.1');
1.2 TCP客户端
var net = require('net');
var client = new net.Socket();
client.setEncoding('utf8');
client.connect(8765,'127.0.0.1',function(){
console.log('connect');
client.write('to server');
client.end('end');
});
client.on('data',function(data){
console.log('receive data from server');
});
1.3 UDP服务器
var dgram = require('dgram');
var server = dgram.createSocket('udp4');
server.on('message',function(msg,rinfo){
console.log(msg);
var buf = new Buffer('测试');
server.send(buf,0,buf.length,rinfo.port,rinfo.address);
});
server.on('listening',function(){
console.log('listen');
});
server.bind(12345,'127.0.0.1');
1.4 UDP客户端
server.on('message',function(msg,rinfo){
console.log(msg);
var buf = new Buffer('测试');
server.send(buf,0,buf.length,rinfo.port,rinfo.address);
});