2022-11-11 来源:华纳网 责任编辑:谷雨老师 人气:
核心提示:大家好,欢迎来到谷雨课堂 上节,我们讲使用fastify搭建http服务器, 本节我们来搭建一个tcp服务器 tcp是物联网中比较底层的协议, 同时也是非常重要的协议, node本身就原生支持tcp // 引入NET const net = require ( net ); // 创建TCP服务器 const server
大家好,欢迎来到谷雨课堂


上节,我们讲使用fastify搭建http服务器,
本节我们来搭建一个tcp服务器
tcp是物联网中比较底层的协议,
同时也是非常重要的协议,
node本身就原生支持tcp
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
// 引入NETconst net = require('net');
// 创建TCP服务器const server = net.createServer(function (client) {console.log('someones connects');
// 接收客户端的数据    client.on('data', function (data) {        setTimeout(() => {            client.write('服务端发送通知');        }, 3000);console.log('服务端接收到来自客户端的数据:', data.toString('utf-8'));    });
// 客户端连接关闭    client.on('close', function (err) {console.log('客户端下线');    });
// 客户端连接错误    client.on('error', function (err) {console.log('客户端连接错误');    });});
// 监听客户端的连接server.listen(    {port: 9001,host: '127.0.0.1',    },function () {console.log('server start listening');    });
//设置监听时的回调函数server.on('listening', function () {const { address, port } = server.address();console.log('server is running: ' + address + ':' + port);});
//设置关闭时的回调函数server.on('close', function () {console.log('sever closed');});
//设置出错时的回调函数server.on('error', function () {console.log('sever error');});
 
没错,
以上就是一个标准的多用户的tcp服务器
而且性能还是非常强劲的!
 

 

 

完整的源代码可以登录【华纳网】下载。
https://www.worldwarner.com/






 





免责声明:本文仅代表作者个人观点,与华纳网无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。