Node.js/TCP:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
 
(未显示同一用户的1个中间版本)
第16行: 第16行:
== 长连接 ==
== 长连接 ==
== 心跳包 ==
== 心跳包 ==
== 断开 ==
断开连接监听。
TODO, thinkjs, 等待详说。
<syntaxhighlight lang="javascript">
this.ctx.req.on('error', () => {
  console.log('req error');
});
this.ctx.req.on('close', () => {
  console.log('req close');
});
this.ctx.res.on('error', () => {
  console.log('res error');
});
this.ctx.res.on('close', () => {
  console.log('res close');
});
this.ctx.socket.on('error', () => {
  console.log('socket error');
});
this.ctx.socket.on('close', () => {
  console.log('socket close');
});</syntaxhighlight>

2022年1月4日 (二) 08:41的最新版本

引言

TCP 保活

注意点:

  1. 防火墙等对于空闲 socket 自动关闭。
  2. 对于非正常断开,服务器并不能检测到,为了回收资源必须提供一种检测机制。

保活的方式

应用层面的心跳机制

  1. 客户端自定义心跳消息头,服务器接收后进行回应。
  2. TCP 协议自带的保活功能。

实现

  1. 客户端意外断开链接的处理方式
Insert comment here

长连接

心跳包

断开

断开连接监听。

TODO, thinkjs, 等待详说。

this.ctx.req.on('error', () => {
  console.log('req error');
});
this.ctx.req.on('close', () => {
  console.log('req close');
});
this.ctx.res.on('error', () => {
  console.log('res error');
});
this.ctx.res.on('close', () => {
  console.log('res close');
});
this.ctx.socket.on('error', () => {
  console.log('socket error');
});
this.ctx.socket.on('close', () => {
  console.log('socket close');
});