Python Websocket无法通过Internet连接

ock*_*888 1 javascript python websocket python-3.x

我只是想通过互联网获得一个非常基本的websocket连接。该代码看起来不错-因为它在连接到localhost时可以工作-但是由于某种原因,当我尝试通过Internet使用它时失败了。我正在使用websockets库,我的服务器如下所示:

#!/usr/bin/env python3

import asyncio
import websockets
from logging import getLogger, INFO, StreamHandler

logger = getLogger('websockets')
logger.setLevel(INFO)
logger.addHandler(StreamHandler())

clients = set()

async def handler(websocket, path):
    global clients
    clients.add(websocket)
    try:
        await asyncio.wait([ws.send("Hello!") for ws in clients])
        await asyncio.sleep(10)
    finally:
        clients.remove(websocket)

start_server = websockets.serve(handler, host='127.0.0.1', port=6969)

asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud)

客户看起来像这样:

<!DOCTYPE html>
<html lang="en"><head>
    <meta charset="UTF-8">
    <title>Chat</title>
</head>

<body style="margin:0">
    <script type="text/javascript">
        var ws = new WebSocket("ws://127.0.0.1:6969/");
        var messages = document.getElementById('messages');
        ws.onmessage = function (event) {
            var messages = document.getElementById('messages');
            var message = document.createElement('li');
            var content = document.createTextNode(event.data);
            message.appendChild(content);
            messages.appendChild(message);
        };
    </script>
    Messages:
    <ul id="messages"><li>Hello!</li></ul>


</body></html>
Run Code Online (Sandbox Code Playgroud)

因此,问题在于上述客户端可以正常工作,直到我在Ubuntu计算机上运行服务器(并且确保将端口6969转发至该计算机)并尝试通过Internet连接。主机名解析工作正常,因为我可以ssh启动服务器,但是尝试连接到Websocket始终会向我显示错误消息:

Firefox can’t establish a connection to the server at ws://<remote server url>:6969/.

或与其他浏览器类似。另外,万一有人怀疑,记录器不会输出任何有用的信息(由于连接失败,服务器不会执行任何操作)。

Rob*_*obᵩ 6

您的电话:

websockets.serve(handler, host='127.0.0.1', port=6969)
Run Code Online (Sandbox Code Playgroud)

提供websockets服务器侦听的特定地址。您的服务器只会监听该地址;到其他地址的任何请求都不会被看到。

来自https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.create_server

所述host参数可以是一个字符串,在这种情况下,TCP服务器绑定到hostport。host参数也可以是字符串序列,在这种情况下,TCP服务器绑定到该序列的所有主机。如果host为空字符串或None,则假定所有接口都将返回多个套接字的列表(最有可能的一个用于IPv4,另一个用于IPv6)。

您已将Web服务器绑定到127.0.0.1,这是一个仅用于引用本地计算机的特殊地址。此地址也称为localhost。没有其他机器可以连接到您的计算机localhost

解决方案是提供一个空字符串或None(默认值)。在这种情况下,您的Web服务器将侦听发送到任何地址的请求。

websockets.serve(handler, port=6969)
Run Code Online (Sandbox Code Playgroud)