You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Deno服务器同一端口处理HTTP与WebSocket连接异常问题

解决Deno单端口同时支持HTTP与WebSocket的连接阻塞问题

问题原因

你的代码处理普通HTTP请求时,默认启用了HTTP/1.1的Keep-Alive长连接机制。当一个TCP连接被用于普通HTTP请求后,客户端会复用该连接发送后续请求,而这个连接已经处于HTTP协议状态,无法再升级为WebSocket协议,导致新的WebSocket连接请求失败。反之,先建立WebSocket连接时,该TCP连接会被WebSocket占用,HTTP请求会使用新的TCP连接,因此不会出现异常。

修正后的代码

在普通HTTP响应中添加Connection: close头,强制关闭TCP连接,避免客户端复用同一连接发送WebSocket请求:

// Accept TCP connections over port 8080
for await (const connection of Deno.listen({ port: 8080 })) {
  // Process all the arriving requests
  for await (const requestEvent of Deno.serveHttp(connection)) {
    // Check for the presence of an upgrade header
    if (requestEvent.request.headers.get('upgrade') === 'websocket') {
      // Provide a WebSocket connection
      const { socket, response } = Deno.upgradeWebSocket(requestEvent.request)
      socket.addEventListener('message', e => { console.log(e.data) })
      requestEvent.respondWith(response)
    } else {
      // Otherwise just respond normally and close the connection
      requestEvent.respondWith(new Response('Hello!', {
        headers: { 'Connection': 'close' }
      }))
    }
  }
}

额外说明

如果需要保留HTTP长连接,需额外处理TCP连接的协议切换逻辑,复杂度会更高。对于小型服务器场景,强制关闭普通HTTP连接的方式简单直接,能有效避免协议冲突问题。

内容的提问来源于stack exchange,提问作者Isti115

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 22:19:59