簡體   English   中英

Python Socketio 未與 JavaScript socket.io-client 連接

[英]Python Socketio not connecting with JavaScript socket.io-client

我想簡單地將 socket.io-client 連接到 python 服務器,但由於某種原因它一直失敗。 最初,我啟動我的 python 服務器,然后在執行該過程后嘗試連接 JavaScript 作為我的客戶端服務器,我看到的是 JavaScript 客戶端服務器一直在嘗試連接並出現以下錯誤:

websocket.js:88 WebSocket 連接到 'ws://localhost:5100/socket.io/?EIO=4&transport=websocket' 失敗:

和 python 服務器也重復以下錯誤:

(10448) 接受 ('127.0.0.1', 61471) 127.0.0.1 - - [01/Feb/2022 15:14:01] "GET /socket.io/?EIO=4&transport=websocket HTTP/1.1" 400 136 0.000000

我正在使用 python3.10 和 socketio 以下文檔:

https://python-socketio.readthedocs.io/en/latest/

還嘗試了版本兼容性:

https://pypi.org/project/python-socketio/

pip3 凍結

我嘗試了 python-engineio 和 python-socketio 的多個版本來匹配我的 socket.io-client 但沒有改進。

eventlet==0.33.0
python-engineio==3.13.0
python-socketio==4.6.1

服務器.py

import eventlet
import socketio

sio = socketio.Server()
app = socketio.WSGIApp(sio)

@sio.event
def connect(sid, environ):
    print('[INFO] Connect to client', sid)

@sio.event
def disconnect(sid):
    print('disconnect ', sid)

#ESI.local 192.168.2.95
if __name__ == '__main__':
    eventlet.wsgi.server(eventlet.listen(('0.0.0.0', 5100)), app)

   

HTML/JavaScript

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
<h1>Socket IO Demo</h1>
    <script type="module">
        import { io } from "https://cdn.socket.io/4.3.2/socket.io.esm.min.js";
        
        const sio = io("http://localhost:5100:", {
            forceJSONP: true,
            secure: true,
            jsonp: true,
            transports: [ "websocket","polling"]
        });

        sio.on("connect", () => {
            console.log("connected");
        });

        sio.on("disconnect", () => {
            console.log("Disconnected");
        });
    </script>
</body>
</html>

如果你想執行 websocket,我建議使用 WebSocket package 內置和 ZBF16D570E652CDB66666gFC16D570E652CDB571

這是我為實現與您想要做的類似的事情所做的事情:

let socket = new WebSocket('ws://localhost:8080'); 
console.log('Created socket');

// Connection opened
socket.addEventListener('open', function (event) {
    socket.send('Hello Server!');
});

// Listen for messages
socket.addEventListener('message', function (event) {
    console.log('Message from server ', event.data);
});

// For example : send array
socket.send(JSON.stringify([1, 2, 3]));

Python 服務器:

from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
from collections import OrderedDict

class Application(WebSocketApplication):
    def on_open(self):
        print("Connection opened")

    def on_message(self, message):
        print("Got message: ", message)
        # self.ws.send(...) to make a response

    def on_close(self, reason):
        print(reason)

WebSocketServer(
    ('localhost', 8080),
    Resource(OrderedDict([('/', Application)]))
).serve_forever()

Gevent(python): https://pypi.org/project/gevent-websocket/

經過多次試驗和錯誤。 我終於破解了它。 這是由於 CORS 而發生的,即使我使用 CORS 谷歌擴展來處理這種情況,但我想這應該在后端處理。 只需將 (cors_allowed_origins="*") 傳遞給 socketio.Server() 即可解決所有問題。

sio = socketio.Server(cors_allowed_origins="*")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM