首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Koa中检测客户端断开连接

在Koa中检测客户端断开连接
EN

Stack Overflow用户
提问于 2020-05-12 06:39:16
回答 1查看 691关注 0票数 1

在发送响应之前,我的node.js Koa服务器如何检测和记录客户端断开连接。

通常顺序是:

request

  • node.js
  1. node.js koa服务器启动
  2. 客户端发送http
  3. koa服务器,用于服务request
  4. node.js koa服务器将响应发送给客户端

如果客户端在2完成后断开连接,但在4完成之前,node.js Koa能检测并记录这一点吗?

我使用这个简单的脚本进行了测试,并从另一个终端运行curl,然后在node.js睡眠的10秒延迟期间,终止ctrl命令。

代码语言:javascript
复制
const Koa = require('koa');
const app = new Koa();

/**
 * synchronously delay/sleep/block for time ms
 */
const delay = time => new Promise(res=> {
    console.log(`About to sleep for ${time} ms`)
    setTimeout(res,time)
});

app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

app.use(async ctx => {
  ctx.req.on('close', () => {
    console.log('Request closed');
  });

  console.log('Hello World Started')

  await delay(10000)

  console.log('Hello World Ended');
  ctx.body = 'Hello World !!!';

});

app.listen(3000, () => console.log('running on port 3000'));

在这两种情况下,只发出一次ctx.req.on('close'事件:

  1. 客户端在发送响应之前断开连接。
  2. 服务器响应仍然连接的客户端,等待响应。

我正在使用:

代码语言:javascript
复制
node --version
v13.8.0

讨论不同版本的节点何时发出req.on(“关闭”)事件,此处为:https://github.com/nodejs/node/issues/31394

假设没有特定的“客户端在您发送响应之前断开连接”事件,那么什么是最好的模式来检测一般情况,这样我就可以记录它。

EN

回答 1

Stack Overflow用户

发布于 2020-05-14 01:47:50

我们可以用一个变量来评估这个问题。当客户端在请求处理完成之前关闭时,下面提到的代码将记录错误消息。这是一种肮脏的修复,但有效。

代码语言:javascript
复制
const Koa = require('koa');
const app = new Koa();

/**
 * synchronously delay/sleep/block for time ms
 */
const delay = time => new Promise(res=> {
    console.log(`About to sleep for ${time} ms`)
    setTimeout(res,time)
});

app.on('error', (err, ctx) => {
    console.error('server error', err, ctx)
});

app.use(async ctx => {
  let requestProcessingCompleted = false    
  ctx.req.on('close', () => {
    console.log('Request closed');
    if(!requestProcessingCompleted){
        console.log("Client connection closed before request processing completed")
    }
  });

  console.log('Hello World Started')

  await delay(10000)

  console.log('Hello World Ended');
  ctx.body = 'Hello World !!!';
  requestProcessingCompleted = true
});

app.listen(3000, () => console.log('running on port 3000'));
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61745372

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档