我正在尝试让 Socket.IO 客户端连接到我使用 aaugustin's websockets library 创建的 Python Websocket 服务器和异步。使用页面上的示例,我创建了以下 Web 套接字服务器:
import asyncio
import websockets
from datetime import datetime
@asyncio.coroutine
def producer():
return str(datetime.now())
@asyncio.coroutine
def handler(websocket, path):
while True:
message = yield from producer()
if not websocket.open:
break
yield from websocket.send(message)
yield from asyncio.sleep(3)
start_server = websockets.serve(handler, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
View 是使用 Flask 提供的,如下所示:
<!doctype html>
<head>
<title>Websocket Client Test</title>
</head>
<body>
<script src="https://cdn.socket.io/socket.io-1.3.5.js"></script>
<script>
console.log(io);
var socket = io("ws://localhost:8765/");
console.log(socket);
</script>
</body>
每当 Socket.IO 尝试连接时,它都会抛出以下错误:
XMLHttpRequest cannot load http://localhost:8765/socket.io/?EIO=3&transport=polling&t=1434254272412-0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5001' is therefore not allowed access. The response had HTTP status code 400.
Access-Control-Allow-Origin 似乎暗示我正在尝试向具有不同主机名的位置发出请求,但我没有这样做。所以我不知道为什么会抛出该错误。我创建了一个可以很好地连接到服务器的 Python 客户端脚本,所以我有点迷失了我所缺少的东西。
最佳答案
The Access-Control-Allow-Origin seems to imply I'm trying to make a request to a location with a different hostname, which I'm not doing.
不同的端口被认为是许多实现的不同来源。来自 https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy :
Two pages have the same origin if the protocol, port (if one is specified), and host are the same for both pages
关于python - 如何使 Socket.IO 客户端连接到 Python3 Websocket 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825825/