我在localhost:5005上运行了websokets模块的python websocket服务器.来自documentation page的代码:

#!/usr/bin/env python

import asyncio
import websockets
import logging

logger = logging.getLogger('websockets')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())

async def echo(websocket):
    async for message in websocket:
        print(message)
        await websocket.send(message)

async def main():
    async with websockets.serve(echo, "localhost", 5005):
        await asyncio.Future()  # run forever

asyncio.run(main())

Clients can access it by connecting to the URL ws://localhost:5005. A sample client code is given in the websockets module documentation page.
The goal is to enable clients to access the server via IIS (Windows native webserver) acting as a reverse proxy, i.e., via the URL ws://localhost/app.

IIS-10 settings:

  • Application Request Routing Cache-->Server Proxy Setting-->Enable proxy
  • Sites-->Default Web Site:我添加了一个名为app的应用程序
  • URL Rewrite:我添加了以下规则:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="ReverseProxy" stopProcessing="true">
                    <match url="(.*)" />
                    <action type="Rewrite" url="http://localhost:5005" logRewrittenUrl="true" />
                </rule>
            </rules>
        </rewrite>
    </system.webServer>
</configuration>

一旦客户端try 连接,它就会断开连接,服务器就会抛出此异常:

= connection is CONNECTING
< GET / HTTP/1.1
< Cache-Control: no-cache
< Connection: Upgrade
< Pragma: no-cache
< Upgrade: websocket
< Accept-Encoding: gzip, deflate, br, peerdist
< Accept-Language: en-US,en;q=0.9
< Host: localhost:5005
< Max-Forwards: 10
< User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
< Origin: null
< Sec-WebSocket-Version: 13
< Sec-WebSocket-Key: /C9ah/z+wAo4mnoACSz2IA==
< Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
< X-Original-URL: /app
< X-Forwarded-For: [::1]:52798
< X-ARR-LOG-ID: 8c59749a-4e5d-43cf-8a5a-c4421cc4ecc8
< X-P2P-PeerDist: Version=1.1
< X-P2P-PeerDistEx: MinContentInformation=1.0, MaxContentInformation=2.0
> HTTP/1.1 101 Switching Protocols
> Upgrade: websocket
> Connection: Upgrade
> Sec-WebSocket-Accept: W9Sttf7fHX3aB9zd4b/PVGt0Ldg=
> Sec-WebSocket-Extensions: permessage-deflate; server_max_window_bits=12; client_max_window_bits=12
> Date: Fri, 15 Jul 2022 19:14:32 GMT
> Server: Python/3.7 websockets/10.3
connection open
= connection is OPEN
! failing connection with code 1006
= connection is CLOSED
x half-closing TCP connection
connection handler failed
Traceback (most recent call last):
  File "C:\Users\amin.ramezanifar\AppData\Roaming\Python\Python37\site-packages\websockets\legacy\protocol.py", line 945, in transfer_data
    message = await self.read_message()
  File "C:\Users\amin.ramezanifar\AppData\Roaming\Python\Python37\site-packages\websockets\legacy\protocol.py", line 1015, in read_message
    frame = await self.read_data_frame(max_size=self.max_size)
  File "C:\Users\amin.ramezanifar\AppData\Roaming\Python\Python37\site-packages\websockets\legacy\protocol.py", line 1090, in read_data_frame
    frame = await self.read_frame(max_size)
  File "C:\Users\amin.ramezanifar\AppData\Roaming\Python\Python37\site-packages\websockets\legacy\protocol.py", line 1149, in read_frame
    extensions=self.extensions,
  File "C:\Users\amin.ramezanifar\AppData\Roaming\Python\Python37\site-packages\websockets\legacy\framing.py", line 70, in read
    data = await reader(2)
  File "C:\Program Files\Python37\lib\asyncio\streams.py", line 677, in readexactly
    raise IncompleteReadError(incomplete, n)
asyncio.streams.IncompleteReadError: 0 bytes read on a total of 2 expected bytes
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "C:\Users\amin.ramezanifar\AppData\Roaming\Python\Python37\site-packages\websockets\legacy\server.py", line 232, in handler
    await self.ws_handler(self)
  File "D:/Robotic Framework/RoboticApps/UI_Framework/server.py", line 12, in echo
    async for message in websocket:
  File "C:\Users\amin.ramezanifar\AppData\Roaming\Python\Python37\site-packages\websockets\legacy\protocol.py", line 482, in __aiter__
    yield await self.recv()
  File "C:\Users\amin.ramezanifar\AppData\Roaming\Python\Python37\site-packages\websockets\legacy\protocol.py", line 553, in recv
    await self.ensure_open()
  File "C:\Users\amin.ramezanifar\AppData\Roaming\Python\Python37\site-packages\websockets\legacy\protocol.py", line 921, in ensure_open
    raise self.connection_closed_exc()
websockets.exceptions.ConnectionClosedError: no close frame received or sent
connection closed

To make sure if IIS settings are correct, I used another websocket library named "simple-websocket-server" from here and it worked fine. Also I tried a simple Node.js server from here and it was successful.
What could be wrong?

推荐答案

阿明(问题作者)和我发现必须禁用WebSocket中的压缩,因为IIS不支持它.

与WebSocket不同,它与其他库一起工作,因为它们不实现压缩或默认情况下不启用压缩.

有关详细信息,请参阅GitHub上的讨论:https://github.com/aaugustin/websockets/issues/1192

Python相关问答推荐

合并与拼接并举

计算空值

有没有办法让Re.Sub报告它所做的每一次替换?

有没有一种方法可以在朗肯代理中集成向量嵌入

为什么我的scipy.optimize.minimize(method=";newton-cg";)函数停留在局部最大值上?

启动线程时,Python键盘模块冻结/不工作

我如何为测试函数的参数化提供fixture 生成的数据?如果我可以的话,还有其他 Select 吗?

这是什么排序算法?(将迭代器与自身合并&&Q;)

如何正确设置ALLOWED_HOST以允许网络中的其他计算机访问Web

更改我的NN中的隐藏层数会导致错误

Python:将带有UNNESTED div标签的html文档解析为dataframe(使用Beautiful Soup )

PythonC扩展比Numba JIT快吗?

真正的Python散布函数

Pandas 替换为另一行中的值

Cdlib和iggraph的信息变化结果不同

基于条件的Pandas 数据框背景 colored颜色

压平JSON后的Pandas 保留柱

在TKinter中将列表显示为多行标签

识别相同的重复值-Pandas

将Hangman游戏中的&替换为所有比赛的玩家猜测