python - python socketio通信与ssl相关问题
问题描述
我正在使用 python socketio 进行通信,它适用于 http。升级它以使用 SSL 时出现问题。
我制作了自签名根证书 (CA),并颁发了 server.cert 和 server.key。我告诉计算机信任 CA。之后,我在 flask-socketio 服务器端添加了 server.cert 和 server.key。代码如下所示:
from flask import Flask, render_template
from flask_socketio import SocketIO
from flask_socketio import Namespace
app = Flask(__name__, template_folder="templates")
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
# Create a URL route in our application for "/"
@app.route('/')
def home():
"""
This function loads the homepage
"""
return render_template('index.html')
class MyCustomNamespace(Namespace):
def on_connect(self):
print("Client just connected")
def on_disconnect(self):
print("Client just left")
def on_messages(self, data):
print(f"\nReceived data from client: \n {data}\n")
return data
socketio.on_namespace(MyCustomNamespace('/channel_A'))
if __name__ == "__main__":
socketio.run(app, host="192.168.0.28", port=2000, certfile="server.crt", keyfile="server.key", server_side=True, debug=True)
#socketio.run(app, host="192.168.0.28", port=2000, debug=True)
客户端连接的代码很简单:
import socketio
sio = socketio.Client()
def message_received(data):
print(f"Message {data} received")
@sio.on('connect', namespace="/channel_A")
def on_connect():
print("Connect...")
@sio.on('disconnect', namespace="/channel_A")
def on_disconnect():
print(f"Disconnected from server")
if __name__ == '__main__':
sio.connect('https://192.168.0.28:2000', namespaces="/channel_A")
emit_times = 0
is_emit = True
data = '{"data": "foobar"}'
while is_emit:
sio.emit("messages", data, namespace="/channel_A", callback=message_received)
emit_times += 1
if emit_times > 1:
is_emit = False
sio.disconnect()
我正在使用 python-socketio ( https://python-socketio.readthedocs.io/en/latest/client.html#disconnecting-from-the-server ) 作为客户端。
服务器启动后,网站运行良好,连接安全。命令行如下所示:
* Restarting with stat
* Debugger is active!
* Debugger PIN: 142-782-563
(3484) wsgi starting up on https://192.168.0.28:2000
当 SocketIO 客户端尝试与服务器连接时,连接被拒绝,在服务器端,最终抛出如下错误:
ssl.SSLError: [SSL: TLSV1_ALERT_UNKNOWN_CA] tlsv1 alert unknown ca (_ssl.c:2488)
我想我可能会错过一些东西。有任何想法吗?提前致谢!
解决方案
这似乎是较新的 SocketIO 版本中的错误。您可以尝试降级到 2.xx:
pip install python-socketio<3.0.0 --force-reinstall
推荐阅读
- android - 在更新回收器视图列表的数据集时,它的滚动跳回顶部(重复)
- python - 不接收带有 Python 请求的 302 状态码
- react-native - react-native android错误:开发服务器返回响应错误代码:404
- laravel - 在 Laravel Blade 中使用 Trait(组件)
- python - 求解变量子集的多元方程
- ruby-on-rails - Rails 6 alpha:Sprockets::FileNotFound
- c# - 自定义形状您的用户控件或面板
- amazon-web-services - 如何用其他 ec2 实例图像替换 ec2 图像?
- node.js - 未处理的拒绝 MongoError: '$inc' 中的美元 ($) 前缀字段 '$inc' 对存储无效
- java - 当我使用千分尺的 PrometheusMeterRegistry 时,指标没有出现在普罗米修斯端点