我只是想通过互联网获得一个非常基本的 websocket 连接。代码看起来不错——因为它在连接到本地主机时有效——但由于某种原因当我尝试通过互联网使用它时失败了。我正在使用 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
in 启动服务器,但尝试连接到 websocket 总是显示错误消息:
Firefox can’t establish a connection to the server at ws://<remote server url>:6969/.
或其他浏览器类似。另外,如果有人想知道,记录器没有输出任何有用的东西(因为连接失败,服务器没有做任何事情)。
最佳答案
你的线路:
websockets.serve(handler, host='127.0.0.1', port=6969)
提供一个特定的地址,websockets 服务器监听这个地址。您的服务器将仅监听该地址;将永远不会看到对任何其他地址的任何请求。
来自 https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.AbstractEventLoop.create_server :
The
host
parameter can be a string, in that case the TCP server is bound tohost
andport
. 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. Ifhost
is an empty string orNone
, all interfaces are assumed and a list of multiple sockets will be returned (most likely one for IPv4 and another one for IPv6).
您已将网络服务器绑定(bind)到 127.0.0.1
,这是一个只指向本地计算机的特殊地址。此地址也称为 localhost
。没有其他机器可以连接到您的 localhost
。
解决方案是提供一个空字符串或None
(默认值)。在这种情况下,您的网络服务器将监听发送到任何地址的请求。
websockets.serve(handler, port=6969)
关于javascript - Python Websockets 无法通过互联网连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45944199/