连接Flask Socket.IO服务器和Flutter [英] Connecting Flask Socket.IO Server and Flutter
问题描述
基本上,我有一个套接字io flask代码:
Basically, I have a socket io flask code:
import cv2
import numpy as np
from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from threading import Lock,Timer as tmr
from engineio.payload import Payload
import base64
from PIL import Image
import io
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@socketio.on('connect')
def connect():
print("a client connected")
@socketio.on('disconnect')
def disconnect():
print('Client disconnected')
@app.route('/')
def hello():
return render_template('index.html')
if __name__ == '__main__':
socketio.run(app,port=port,host= '0.0.0.0')
当我尝试将其连接到javascript时,此代码工作正常
This code is working fine when I try to connect it to javascript
但是在扑朔迷离中我无法实现
However in flutter I can not achieve that
我有一个有状态的Widget,里面有一个按钮当按下按钮时,我正在使用此功能将其连接到我的插座上
I have stateful Widget that has a button in it And I am using this function to connect to my socket when the button is pressed
import 'package:socket_io_client/socket_io_client.dart' as IO;
IO.Socket socket;
connectToSocket() {
socket = IO.io("http://10.0.2.2:6400", <String, dynamic>{
'transports': ['websocket', 'polling'],
});
socket.connect();
}
我无法连接它,请帮助我.
I can not connect it please help me.
推荐答案
我知道这是一个比较老的问题,但是希望这个答案可以对以后的工作有所帮助.
I know this is an older question but hopefully this answer will help someone down the road.
该问题可能是由于缺乏对抖动轮询的支持所致.
The issue may be caused by the lack of support for polling in flutter.
来自: https://github.com/rikulo/socket.io-client-dart#usage-flutter
在Flutter环境中.它仅适用于dart:io websocket,不适用于dart:html websocket,因此在这种情况下,您必须在创建套接字实例时添加'transports':['websocket'].
In Flutter env. it only works with dart:io websocket, not with dart:html websocket, so in this case you have to add 'transports': ['websocket'] when creates the socket instance.
IO.Socket socket = IO.io('http://localhost:3000', <String, dynamic>{
'transports': ['websocket'],
'extraHeaders': {'foo': 'bar'} // optional
});
默认的Flask开发服务器不支持websocket,因此您需要使用其他服务器.幸运的是,让Eventlet与Flask一起使用很简单.您所需要做的就是使用pip安装eventlet软件包.
The default Flask development server doesn't support websockets so you'll need to use another server. Thankfully it's simple to get eventlet working with Flask. All you should have to do is install the eventlet package using pip.
pip install eventlet
一旦安装了eventlet,socketio将在运行服务器时检测并使用它.
Once eventlet is installed socketio will detect and use it when running the server.
您可以使用chrome仔细检查正在使用的传输方式.在Windows中打开您的Chrome开发工具 Ctrl + Shift + I
并转到网络标签.在每个网络请求上,您应该会看到 transport = polling
或 transport = websocket
You can use chrome to double check what transport method is being used. Open your chrome dev tools Ctrl+Shift+I
in Windows and go to the Network tab. On each network request you should see either transport=polling
or transport=websocket
这篇关于连接Flask Socket.IO服务器和Flutter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!