我有flask服务器,使用rest api提供角前端服务。我想添加从服务器到客户端的推送机制来处理实时数据。
我尝试使用flask socketio python和socket。angular中的Io-client,但不会发出数据请注意,我尝试将socket io添加到主应用flask
服务器:
app = create_app()
socketioR.__init__(app, cors_allowed_origins="*",logger=True, engineio_logger=True,log_output=True)
manager = Manager(app)
manager.add_command('runserver', Server(host='localhost', port=settings.SYSTEM_PORT, threaded=True))
if __name__ == '__main__':
manager.run()
socketioR.run(app, debug=True)
排放功能:
def send_data():
try:
socketioR.send('message', {'data': 42}, namespace='/', broadcast=True)
except Exception as e:
print(e)
角客户:
import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import io from "socket.io-client";
// import { Socket } from 'ngx-socket-io';
@Injectable({
providedIn: 'root'
})
export class PushService {
public message$: BehaviorSubject<any> = new BehaviorSubject('');
private socket: any;
constructor() {
try {
this.socket = io('http://localhost:8119', {
extraHeaders: {
'Access-Control-Allow-Origin': "*"
}
});
this.socket.on('connect_error',(message: any)=>
console.log(message))
}
catch (ex) {
console.log(ex)
}
this.getNewMessage()
}
public getNewMessage(){
this.socket.on('message', (message: any) =>{
this.message$.next(message);
});
return this.message$.asObservable();
};
}
在服务器中重复下面的日志:
INFO:werkzeug:127.0.0.1 - - [17/Jul/2022 11:45:22] "OPTIONS /socket.io/?EIO=4&transport=polling&t=O8BLMRO HTTP/1.1" 200 -
INFO:werkzeug:127.0.0.1 - - [17/Jul/2022 11:45:22] "GET /socket.io/?EIO=4&transport=polling&t=O8BLMRO HTTP/1.1" 200 -
在angular客户端中,此错误由connection - parser error:
引发。Error: server error
at Socket.onPacket (socket.js:317:1)
at Emitter.emit (index.mjs:136:1)
at Polling.onPacket (transport.js:105:1)
at callback (polling.js:118:18)
at Array.forEach (<anonymous>)
at Polling.onData (polling.js:121:53)
at Emitter.emit (index.mjs:136:1)
at Request.onLoad (polling.js:365:18)
at xhr.onreadystatechange [as __zone_symbol__ON_PROPERTYreadystatechange] (polling.js:301:26)
at XMLHttpRequest.wrapFn (zone.js:766:1)
这里有人能告诉我我哪里错了吗?或者为这个要求提供其他不同的解决方案?卸载并安装flask-SocketIO
包即可解决此问题。