烧瓶无法从套接字接收消息

时间:2019-04-21 15:38:14

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

—————————————————问题更新2 ——————————————————

大家好,我的问题已经解决。感谢米格尔。他的建议非常有用。 在5月update2中,我在路线Int中忘记了@。

——————————————————原始问题————————————————————

我写了一个服务器烧瓶,我需要一种方法来处理我的数据,我选择了socketio。 我的父亲是这样的:

@socketio.on()

在runserver.py

/mysite
..runserver.py
....__init__.py
....views.py
../templates
....dice.html

初始 .py

from mysite import app
from flask_socketio import SocketIO
socketio = SocketIO(app)
if __name__ == '__main__':
    socketio.run(app)

观看次数

from flask_socketio import SocketIO

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

在dice.html

from mysite import app,socketio

@app.route('/dice',methods = ['GET','POST'])
def dice():
    return render_template('dice.html', form=form)

@socketio.on('DiceRequest',namespace='/dice')
def diceResult(message):
    emit('DiceResult',{'data':message['data']})

我可以捕获这样的http pack数据

<script>
    $(document).ready(function () {
        namespace = '/dice';
        var socket = io.connect('http://localhost:' + '5000' + namespace);
        socket.on('DiceResult', function (msg) {
            $('#log').append('<br><input type="text">' + $('<div/>').text(msg.data).html());
        });
        $('form#emit').submit(function (event) {
            socket.emit('DiceRequest', { data: $('#emit_data').val() });
            return false;
        });
    });
</script>
    <form id="emit" method="POST" action='#'>
        <input type="text" name="emit_data" id="emit_data" placeholder="Message">
        <input type="submit" value="Echo">
    </form>
<h2>Receive:</h2>
<div id="log"></div>

当我在views.pydef diceResult(message):中设置断点时,我无法中断程序。所以我认为我的后台无法接收我的数据。

——————————————————问题更新1 ——————————————————

我尝试像Miguel的建议一样重写代码,但是我仍然无法接收数据。 REQUEST: Request URL: http://localhost:5000/socket.io/?EIO=3&transport=polling&t=1555859308868-6&sid=7227db4c2a424529b365c70e631f7a89 Request Method: POST Status Code: 200 OK Remote Address: 127.0.0.1:5000 Referrer Policy: no-referrer-when-downgrade HEADER: Content-type: text/plain;charset=UTF-8 Origin: http://127.0.0.1:5000 Referer: http://127.0.0.1:5000/dice User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 DATA: 36:42/dice,["DiceRequest",{"data":"2"}] RESPONSE: HEADER: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://127.0.0.1:5000 Connection: close Content-Type: text/plain Date: Sun, 21 Apr 2019 15:08:29 GMT Server: Werkzeug/0.15.2 Python/3.6.8 DATA: OK

中的代码
__init__.py

from flask_socketio import SocketIO app = Flask(__name__) socketio = SocketIO(app)

runserver.py

from mysite import app,socketio socketio.run(app)

views.py

和我的@app.route('/dice',methods=['GET','POST']) def dice(): form = diceForm() return render_template('dice.html',form=form) socketio.on('DiceRequest',namespace='/dice') def DiceResult(message): emit('DiceResult',{'data':message['data']}) 这样

dice.html

0 个答案:

没有答案