码迷,mamicode.com
首页 > Web开发 > 详细

4.nodejs权威指南--TCP和UDP

时间:2015-11-01 15:07:39      阅读:337      评论:0      收藏:0      [点我收藏+]

标签:

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);

});

4.nodejs权威指南--TCP和UDP

标签:

原文地址:http://www.cnblogs.com/SLchuck/p/4927611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!