简体   繁体   English

flask-socketio 事件未到达前端

[英]flask-socketio events not reaching frontnend

I have created a small webapp, and want to use socketio.我创建了一个小型 webapp,并想使用 socketio。

I use socket.io v.3 in my javascript, and flask.socketio v 5.0.1 with enginoio v 4.0.0 and python-socketio v 5.0.4我在我的 javascript 和 flask.socketio v 5.0.1 和 enginoio v 4.0.4 和 python-socket 中使用 socket.io v.3。

I can successfully emit events from the client to the server, though i cannot communicate back.我可以成功地将事件从客户端发送到服务器,但我无法回复。

My flask code is:我的 flask 代码是:

@socketio.on('submit')
def submit(data):
    print('received message: button click')
    print(data)
    emit('submit',{'complete': 66, 'stage': 'deploying groups'})
    print('data send')

My javascript looks like this:我的 javascript 看起来像这样:

    var socket = io();
    socket.on('*', function(data) {
      document.getElementById("Project Name").value = 'test'
      });
    socket.on('submit', function(data) {
      document.getElementById("Project Name").value = 'test'
      });

The server side code executes, and i see data send in the flask console log, though the client side never does anything.服务器端代码执行,我在 flask 控制台日志中看到数据发送,尽管客户端从不做任何事情。 I tried running the command in the console, and i successfully set the name of the field.我尝试在控制台中运行命令,并成功设置了字段的名称。 I've also tried copy pasting the socket.on definitions into the console, but this did not work either.我也尝试将 socket.on 定义复制粘贴到控制台中,但这也不起作用。

If i run this command in the console, i see the defined function:如果我在控制台中运行此命令,我会看到定义的 function:

 socket.listeners("submit");

I would expecft the value of "project name" to update to test我希望更新“项目名称”的值以进行测试

I figured out what my problem was, I had another function that also created a socket.我弄清楚我的问题是什么,我有另一个 function 也创建了一个套接字。

I figured out you should only run var socket = io();我发现你应该只运行var socket = io(); once in your code, not once per function.一次在您的代码中,而不是每个 function 一次。

My problem was I started making app-> backend work and got stuck when trying to return something, due to reinitiating the socket before I received an answer from the backend.我的问题是我开始让 app-> 后端工作并且在尝试返回某些东西时卡住了,因为在我收到来自后端的答案之前重新启动了套接字。

TLDR; TLDR; only define the socket once per page, not once per function.每页只定义一次套接字,而不是每个 function 一次。 Defining it again will reset your session.再次定义它将重置您的 session。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM