网络编程示例

1. 网络编程

1.1 TCP

//server

var net = require('net');

 

var server = net.createServer(function(socket){

      socket.on('data',function(data){

             socket.write('hello world');

      });

     

      socket.on('end',function(){

             console.log('end');

      });

     

      socket.write('welcome');

});

 

server.listen(8000,'127.0.0.1',function(){

      console.log('server bound');

});

 

//client

var net = require('net');

 

var client = net.connect(8000,'127.0.0.1',function(){

      console.log('client connected');

      client.write('hi!\r\n');

});

 

client.on('data',function(data){

      console.log(data.toString());

      client.end();

});

 

client.on('end',function(){

      console.log('client end');

});

1.2 UDP

//server

var dgram = require('dgram');

 

var server = dgram.createSocket('udp4');

 

server.on('message',function(msg,rinfo){

      console.log(msg+rinfo.address+rinfo.port);

});

 

server.on('listening',function(){

      var address = server.address();

      console.log(address.address+address.port);

});

 

server.bind(9000,'127.0.0.1');

 

//client

var dgram = require('dgram');

 

var client = dgram.createSocket('udp4');

var message = new Buffer('hello world');

client.send(message,0,message.length,9000,'127.0.0.1',function(err,bytes){

      client.close();

});

1.3 HTTP

//server

var http = require('http');

var server = http.createServer(function(req,res){

      res.writeHead(200,{'Content-Type':'text/plain'});

      var chunks = [];

      req.on('data',function(chunk){

             chunks.push(chunk);

      })

      req.on('end',function(){

             var buffer = Buffer.concat(chunks);

             res.end('hello world!\r\n');

      });

     

});

 

server.listen(9999,'127.0.0.1');

 

//client

var options = {

      hostname:'127.0.0.1',

      port:9999,

      path:'/',

      method:'GET'

}

 

var req = http.request(options,function(res){

      console.log(res.statusCode);

      console.log(JSON.stringify(res.headers));

      res.setEncoding('utf8');

      res.on('data',function(chunk){

             console.log(chunk);

      })

});

 

req.end();

posted @   S&L·chuck  阅读(240)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示