Python Websockets 无法通过互联网连接 [英] Python Websockets can't connect over internet

查看:67
本文介绍了Python Websockets 无法通过互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm just trying to get a very basic websocket connection over internet. The code seems fine - because it works when connecting to localhost - but for some reason fails when I try to use it over the internet. I'm using the websockets library, and my server looks like this:

#!/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 总是向我显示错误消息:

So the issue is that the client above works fine, until I run the server on my Ubuntu machine (and I've made sure to forward port 6969 to that machine) and try to connect over the internet. Hostname resolution is working fine, because I can ssh in to start the server, but trying to connect to the websocket always shows me the error message:

Firefox 无法与位于 ws://:6969/的服务器建立连接.

或类似的其他浏览器.此外,万一有人想知道,记录器没有输出任何有用的信息(因为连接失败,服务器没有做任何事情).

or similiar for other browsers. Also, in case anyone was wondering, the logger isn't outputting anything useful (since the connection is failing the server isn't doing anything).

推荐答案

您的线路:

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

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

provides a specific address on which the websockets server listens. Your server will only listen on that address; any requests to any other address will never be seen.

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

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

The host parameter can be a string, in that case the TCP server is bound to host and port. The host parameter can also be a sequence of strings and in that case the TCP server is bound to all hosts of the sequence. If host is an empty string or None, all interfaces are assumed and a list of multiple sockets will be returned (most likely one for IPv4 and another one for IPv6).

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

You have bound your webserver to 127.0.0.1, which is a special address that only ever refers to the local machine. This address is also known as localhost. No other machine can ever connect to your localhost.

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

The solution is to provide an empty string or None (the default value). In this case, your web server will listen for requests sent to any address.

websockets.serve(handler, port=6969)

这篇关于Python Websockets 无法通过互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆