简体   繁体   中英

How to make a Socket.IO client connect to a Python3 Websocket server

I'm attempting to get a Socket.IO client to connect to a Python Websocket server I created using aaugustin's websockets library and asyncio. Using the example on the page I created the following web socket server:

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()

The view is served up using Flask and looks like the following:

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

Whenever Socket.IO tries to connect, it throws the following error:

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.

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. So I don't know why its throwing that error. I created a Python client script that connects to the server just fine, so I'm a little lost as to what I'm missing.

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.

Different port is considered a different origin for lots of implementations. From 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

I believe this is impossible. Socket.io implements its own protocol, so you cannot use socket.io-client with a non-socket.io server. See: https://stackoverflow.com/a/19522754/627663

Instead of using socket.io-client, you can use the standard javascript websocket API which works in most browsers these days.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM