Flask-SocketIO没有收到消息

时间:2018-05-30 22:39:19

标签: javascript python flask socket.io flask-socketio

SocketIO版本1.3.6

Python 3.6

我在我的python应用程序中使用Flask-SocketIO来发送和接收消息。我能够发送消息(我在终端看到输出),但客户端没有收到消息(控制台没有输出)。

$(document).ready(function() {
  var socket = io.connect('http://localhost:5000/');
  socket.on('connect', function() {
    console.log("connected")
  });
  socket.on('message', function(msg) {
    console.log('Received message');
  });
  $('#submitmsg').on('click', function() {
    socket.send($('#usermsg').val());
    $('#usermsg').val('');
  });
});

聊天窗口HTML:

<div id="wrapper">
    <div id="menu">
        <p class="welcome">Welcome<b></b></p>
        <p class="logout"><a id="exit" href="#">Exit</a></p>
        <div style="clear:both"></div>
    </div>

    <div id="chatbox"></div>

    <form name="message" action="">
        <input name="usermsg" type="text" id="usermsg" size="63" />
        <input name="submitmsg" type="submit" id="submitmsg" value="Send" />
    </form>
</div>

编辑:添加服务器代码:

from flask import Flask, render_template
from flask_socketio import SocketIO, send

app = Flask(__name__)
socketio = SocketIO(app)

@app.route("/")
def index():
    return render_template('index.html')

@socketio.on('message')
def handleMessage(msg):
    print('Message: ' + msg)
    send(msg, broadcast=True)

if __name__ == '__main__':
    socketio.run(app)

如果收到的消息有效,我应该在浏览器控制台中看到'Received message',但我看不到它。我错过了什么?有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您使用<input name="submitmsg" type="submit" id="submitmsg" value="Send"/>提交表单,它会生成POST请求,然后您的页面将重新加载,这就是为什么您的页面中的JS函数socket.on()将不会被调用。

显然,使用Flask-SocketIO,您无需使用POST请求。因此,只需将其更改为<button name="submitmsg" id="submitmsg">Send</button>并删除<form>标记,即:

<div id="wrapper" display = 'none'>
    ...
    <div id="chatbox"></div>

    <input name="usermsg" type="text" id="usermsg" size="63"/>
    <button name="submitmsg" id="submitmsg">Send</button>
</div>
相关问题