如何解决如何使用flask socket.io连接服务器?
我是套接字的初学者,并且使用python flask框架
下面是我的烧瓶 __初始化__。py 文件
from flask_socketio import SocketIO
from threading import Thread,Event
app = Flask(__name__)
socketio = SocketIO(app,async_mode=None,logger=True,engineio_logger=True)
thread = Thread()
thread_stop_event = Event()
def notificationDetails():
while not thread_stop_event.isSet():
print("Thread call")
socketio.emit('notification',{'notification_list': 5},namespace='/socket')
socketio.sleep(5)
@app.route('/')
def home():
return render_template('index.html')
@socketio.on('connect',namespace='/socket')
def notification_connect():
# need visibility of the global thread object
global thread
print('Client connected')
#Start the notification details thread only if the thread has not been started before.
if not thread.isAlive():
print("Starting Thread")
thread = socketio.start_background_task(notificationDetails)
@socketio.on('disconnect',namespace='/socket')
def notification_disconnect():
print('Client disconnected')
以下是烧瓶 run.py 文件
from app import app,api,socketio
if __name__ == '__main__':
socketio.run(app,host='0.0.0.0',port='8002',debug=True)
下面给出的是桌面 html 文件
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>SocketIO example</title>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js">
</script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {
// sending a connect request to the server.
eg: http://0.0.0.0:8002/socket consider as a server ip and port
var socket = io.connect('http://0.0.0.0:8002/socket',{'transports': ['websocket','polling']});
var numbers_received = [];
//receive details from server
socket.on('notification',function(msg) {
console.log("Received number",msg);
});
});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage">
<button id="sendbutton">Send</button>
<div id="log"></div>
</body>
</html>
一旦我运行 html 文件产生以下错误
index.js:83 WebSocket connection to 'ws://0.0.0.0:8002/socket.io/?EIO=3&transport=websocket'
失败:WebSocket握手时出错:意外的响应代码:400
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。