python - 如何使 Socket.IO 客户端连接到 Python3 Websocket 服务器

标签 python sockets flask socket.io python-3.4

我正在尝试让 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/

相关文章:

python - Ubuntu 12.04 上的 SHOGUN

python - 如何在应用程序外部访问 Flask 应用程序配置?

javascript - 如何将文本输入绑定(bind)到同一 html 页面上的另一个 div

c++ - SSL 与加密套接字

python - Socket没有属性AF_INET?

python - flask-restful - 当前请求的资源类

python - 将一列多边形从字符串转换为 GeoPandas 几何

python - cv2计算密集对象

python - 为什么我在使用 Google Protocol Buffers 时会看到 "cannot import name descriptor_pb2"错误?

python - 为什么我会看到 'connection reset by peer' 错误?