简体   繁体   English

Python / JavaScript - WebSockets 连接问题

[英]Python / JavaScript - WebSockets connection problem

I am having several errors with a WebSockets server.我在使用WebSockets服务器时遇到了几个错误。

Previously, I had a lot of problems in acknowledging the server when a connection was established.以前,我在建立连接时确认服务器时遇到了很多问题。 In the bind address, I have the empty string which is equal to 0.0.0.0 so I thought that the problem may come from there.在绑定地址中,我有一个等于0.0.0.0的空字符串,所以我认为问题可能来自那里。 For now, the client can only know that it has been connected when the server stops the time async function.目前,客户端只能在服务器停止time异步 function 时知道它已连接。 I sometimes get the error我有时会收到错误

send.html:14 WebSocket connection to ws://86.205.245.32:5678/ failed: WebSocket opening handshake timed out

but rarely.但很少。

I have lots of questions that can maybe answer this post.我有很多问题可以回答这个帖子。

  • Can using subprotocol help?可以使用子协议帮助吗? If yes, how to use it with a Python server?如果是,如何将它与 Python 服务器一起使用?

  • Can using WSS help?可以使用 WSS 帮助吗?

  • Do I need to change the bind IP of 0.0.0.0 to another?我是否需要将0.0.0.0的绑定 IP 更改为另一个?

The Server服务器

print("start serveur")
import time, websockets, asyncio

async def time(websocket, path):
    print("connect")
    print(websocket)
    print(await websocket.recv())
start_server = websockets.serve(time, "", 5678)
loop=asyncio.get_event_loop() 

loop.run_until_complete(start_server)


loop.run_forever()

Server's Traceback服务器的回溯

Error in connection handler
Traceback (most recent call last):
  File "/usr/lib/python3.5/asyncio/tasks.py", line 241, in _step
    result = coro.throw(exc)
  File "/usr/local/lib/python3.5/dist-packages/websockets/protocol.py", line 674, in transfer_data
    message = yield from self.read_message()
  File "/usr/local/lib/python3.5/dist-packages/websockets/protocol.py", line 742, in read_message
    frame = yield from self.read_data_frame(max_size=self.max_size)
  File "/usr/local/lib/python3.5/dist-packages/websockets/protocol.py", line 815, in read_data_frame
    frame = yield from self.read_frame(max_size)
  File "/usr/local/lib/python3.5/dist-packages/websockets/protocol.py", line 884, in read_frame
    extensions=self.extensions,
  File "/usr/local/lib/python3.5/dist-packages/websockets/framing.py", line 99, in read
    data = yield from reader(2)
  File "/usr/lib/python3.5/asyncio/streams.py", line 668, in readexactly
    yield from self._wait_for_data('readexactly')
  File "/usr/lib/python3.5/asyncio/streams.py", line 458, in _wait_for_data
    yield from self._waiter
  File "/usr/lib/python3.5/asyncio/futures.py", line 380, in __iter__
    yield self  # This tells Task to wait for completion.
  File "/usr/lib/python3.5/asyncio/tasks.py", line 304, in _wakeup
    future.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 285, in result
    raise CancelledError
concurrent.futures._base.CancelledError

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/websockets/server.py", line 169, in handler
    yield from self.ws_handler(self, path)
  File "webserveur.py", line 8, in time
    print(await websocket.recv())
  File "/usr/local/lib/python3.5/dist-packages/websockets/protocol.py", line 434, in recv
    yield from self.ensure_open()
  File "/usr/local/lib/python3.5/dist-packages/websockets/protocol.py", line 658, in ensure_open
    ) from self.transfer_data_exc
websockets.exceptions.ConnectionClosed: WebSocket connection is closed: code = 1006 (connection closed abnormally [internal]), no reason

The Client客户端

<script>
    alert("hello");

    var ws = new WebSocket("ws://86.205.245.32:5678/"  );//1*
        
    ws.onopen = function (event) {
       alert("had a handshake answer that cause a connection");
       ws.send("hello");
    }

</script>

WebSockets Request WebSockets 请求

General
Request URL: ws://86.205.245.32:5678/
Request Headers
Provisional headers are shown
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en;q=0.9,en-US;q=0.8,fr;q=0.7
Cache-Control: no-cache
Connection: Upgrade
Host: 86.205.245.32:5678
Origin: file://
Pragma: no-cache
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits
Sec-WebSocket-Key: M+CfTACesBfbhkWnFclrsA==
Sec-WebSocket-Version: 13
Upgrade: websocket
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36

I want to use DMZ because my network is very strange with lots of protection, so I think that putting the server in a Demilitarize zone will help.我想使用DMZ ,因为我的网络很奇怪,有很多保护,所以我认为将服务器置于非军事区会有所帮助。 For now, I can't tell you if it will be helpful because for now when the client execute the line 1* see on the client code it can't connect to the server.目前,我无法告诉您它是否有帮助,因为目前当客户端执行第1* see on the client code ,它无法连接到服务器。 What is strange is that without DMZ and the server on a Windows computer, it's the same but for sending data, the client can only see the data of the server when the server closes the connection.奇怪的是,Windows电脑上没有DMZ和服务器,都是一样的,只是为了发送数据,客户端只有在服务器关闭连接时才能看到服务器的数据。

What did I try我尝试了什么

  • I tried to deactivate the firewall我试图停用防火墙
  • I asked questions on StackOverflow我在 StackOverflow 上提问

I often have this issues when I close the server during the client execution, even if it doesn't execute the block time that prints print("connect") :当我在客户端执行期间关闭服务器时,我经常遇到这个问题,即使它没有执行打印print("connect")的阻塞time

Task was destroyed but it is pending!
task: <Task pending coro=<WebSocketServerProtocol.handler() running at /usr/local/lib/python3.5/dist-packages/websockets/server.py:117> wait_for=<Future pending cb=[Task._wakeup()]>>

I also changed the client's code as follows but without success.我还按如下方式更改了客户端的代码,但没有成功。

var ws = new WebSocket("ws://86.205.245.32:5678/"),
        messages = document.createElement('ul');

        ws.onopen = function (event) {
        alert("connect");
        ws.send("hello");
        
        }

The Hardware硬件

  • A Windows computer (client)一台Windows电脑(客户端)

  • A Rasberry Pi (server)树莓派(服务器)

Thanks for helping and let me know if you already had this issue and what have you done to solve it.感谢您的帮助,让我知道您是否已经遇到此问题以及您采取了哪些措施来解决它。 Or if you have found errors in the code that could cause this type of problem或者,如果您在代码中发现可能导致此类问题的错误

THANKS谢谢

I tried to reproduce your issue, but my opinion is that your problem is caused by your network infrastructure.我试图重现您的问题,但我认为您的问题是由您的网络基础设施引起的。

The server and the client are very basic and they work smoothly.服务端客户端都很基础,运行流畅。

Divide your problem into different phases:将您的问题分为不同的阶段:

  1. Use your local environment to debug the code ( client and server in localhost , on your PC)使用您的本地环境调试代码(在您的 PC 上的localhost中的客户端服务器
  2. Use your local network to have the first segregation between the client and the server使用您的本地网络在客户端服务器之间进行第一次隔离
  3. Use some free plans on Cloud Providers to test extended networking (AWS, GCP, DigitalOcean)使用 Cloud Providers 上的一些免费计划来测试扩展网络(AWS、GCP、DigitalOcean)

Some suggestions may be:一些建议可能是:

  • Disable completely the Windows Firewall完全禁用 Windows 防火墙
  • Check out that you don't have Firewalls on your Linux Distro (UFW, IPTables...)检查您的 Linux 发行版(UFW、IPTables ......)上没有防火墙
  • Use the LAN IP of your Raspberry Pi for testing instead of its public IP使用 Raspberry Pi 的 LAN IP 进行测试,而不是其公共 IP
  • Make sure that in your Livebox Play you don't have a Firewall in place or some routing rules确保在Livebox Play中没有设置防火墙或某些路由规则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM