Python Websockets无法通过Internet连接

时间:2017-08-29 16:34:24

标签: javascript python python-3.x websocket

我只是想通过互联网获得一个非常基本的websocket连接。代码看起来很好 - 因为它在连接到localhost时起作用 - 但是当我尝试在互联网上使用它时出于某种原因失败了。我正在使用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()

,客户端看起来像这样:

<!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>

所以问题是上面的客户端工作正常,直到我在我的Ubuntu机器上运行服务器(并且我确保将端口6969转发到该机器)并尝试通过互联网连接。主机名解析工作正常,因为我可以ssh启动服务器,但尝试连接到websocket总是显示错误消息:

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

或类似于其他浏览器。此外,如果有人想知道,记录器没有输出任何有用的东西(因为连接失败,服务器没有做任何事情)。

2 个答案:

答案 0 :(得分:3)

你的专栏:

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

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

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

  

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

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

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

websockets.serve(handler, port=6969)

答案 1 :(得分:-2)

WS服务器随机发送消息

导入异步 导入日期时间 随机导入 导入websockets

异步定义时间(网络套接字,路径):     而True:         现在= datetime.datetime.utcnow()。isoformat()+'Z'         等待websocket.send(现在)         等待asyncio.sleep(random.random()* 3)

start_server = websockets.serve(时间,'127.0.0.1',6969)

asyncio.get_event_loop()。run_until_complete(启动服务器) asyncio.get_event_loop()。run_forever()

尝试一下,这样可以消除问题

相关问题