0

我正在尝试创建从 Brython 到运行 Flask 和 Flask-SocketIO 的本地服务器的 Websocket 连接。Brython 代码可以连接到 Websocket 回显服务器,但在尝试使用本地服务器时失败,错误代码为“失败:WebSocket 握手期间出错:意外响应代码:200”

客户端(使用 Brython):

def open_connection(event):
    global ws

    if not websocket.supported:
        alert("WebSocket is not supported by your browser")
        return

    # open a web socket
    # wss is websocket over SSL, ws is unencrypted 
    ws = websocket.WebSocket('ws://192.168.9.121:3000/message')
    #ws = websocket.WebSocket("wss://echo.websocket.org")
    print(ws)

    # bind functions to web socket events
    ws.bind('open', on_open)
    ws.bind('message', on_message)
    ws.bind('close', on_close)

服务器端:

 --- IMPORTS ---
from flask import Flask, render_template
from flask_socketio import SocketIO, emit


# --- CONSTANTS ---
HOST = '0.0.0.0'
PORT = 3000


# --- GLOBALS ---
app = Flask(__name__)
app.config['SECRET_KEY'] = 'xxxxxxx'
socketio = SocketIO(app)


# --- ROUTES ---
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/message')
def message():
    return render_template('message.html')


# --- SOCKETS ---
@socketio.on('connect')
def connect():
    print('Connected')
    emit('broadcast', {'data': 'Connected'}, broadcast=True)

@socketio.on('disconnect')
def disconnect():
    print('Disconnected')
    emit('broadcast', {'data': 'Disconnected'}, broadcast=True)

@socketio.on('message')
def handle_message(message):
    emit('broadcast', {'data': message['data']}, broadcast=True)

@socketio.on_error()
def error(e):
    print('Error', e)


# --- MAIN ---
if __name__ == '__main__':
    # app.run(host=HOST, port=PORT)
    print('Connecting - ', HOST,  ':',  PORT)
    socketio.run(app, host=HOST, port=PORT)

尝试连接时出现的错误代码是:brython.js:8666 WebSocket connection to 'ws://192.168.9.121:3000/message' failed: Error during WebSocket handshake: Unexpected response code: 200

4

3 回答 3

1

注意:Socket.IO 不是 WebSocket 实现。尽管 Socket.IO 确实尽可能使用 WebSocket 作为传输手段,但它会为每个数据包添加一些元数据:数据包类型、命名空间和需要消息确认时的 ack id。这就是为什么 WebSocket 客户端将无法成功连接到 Socket.IO 服务器,而 Socket.IO 客户端也将无法连接到 WebSocket 服务器(如 ws://echo.websocket.org)。

有了这个解释,您需要在 Brython 中以某种方式使用 socket.io 客户端,该客户端当前不可用。

于 2020-09-13T17:43:22.707 回答
0

socket.io 与 WebSockets 不同,但它确实在 WebSockets 上工作

于 2020-09-10T21:06:04.007 回答
0

正如在其他答案中所说,您使用的是基本的网络套接字,而 socketio 有自己的协议。您需要使用 socketio 库。

Brython 支持调用 JS函数和库。

这是一个连接到我的flask-socketio后端的brython片段。

...
<html>
<head>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/brython/3.9.5/brython.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/3.0.4/socket.io.js" integrity="sha512-aMGMvNYu8Ue4G+fHa359jcPb1u+ytAF+P2SCb+PxrjCdO3n3ZTxJ30zuH39rimUggmTwmh2u7wvQsDTHESnmfQ==" crossorigin="anonymous"></script>
</head>
<body>
    <script type="text/python">
        from browser import window, alert

        io = window.io
        socket = io()
        def on_connect():
            alert('connected in Brython')
            socket.emit('join', {'room': 'asd'})

        socket.on('connect', on_connect)
    </script>
</body>
</html>

如果你仍然有问题,让它与普通的 JS 一起工作,以证明它不是别的东西。

JS等价物

<script type="text/javascript">
    var socket = io();
    socket.on('connect', function() {
        alert('connected in JS');
        socket.emit('join', {room: 'asd'});
    });
</script>
于 2021-08-30T04:39:19.570 回答