更改路由并使用socketio发送消息,但是socketio正在工作

时间:2018-09-16 18:55:33

标签: python flask socket.io flask-socketio

<!DOCTYPE html>
<html>
    <head>
        <title>Login</title>
    <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>

   <script>
        document.addEventListener('DOMContentLoaded',()=>{

            var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);

            socket.on('connect',()=>{
                console.log('connected');
               document.querySelector('#submit').onclick =() =>{
                const user= document.querySelector('#user').value;
                const room = document.querySelector('#room').value;
                socket.emit('join',{'user':user,'room':room});
                console.log('emitted');
                return false;
               };

            });

        });

    </script>

    </head>
    <body>
    <form id="new-task" action="{{ url_for('chat') }}" method="post">
        <input type="text" autocomplete="off" autofocus id="user" placeholder="username"> 
        <input type="text" autocomplete="off" autofocus id="room" placeholder="room">
        <input type="submit" id="submit" value="join">     
    </form> 
    </body>
</html>

localhost:5000打开index.html页,当我单击“提交”时,只有socketio可以工作,但是url未被更改。

import os
import requests

from flask import Flask,jsonify,render_template,request
from flask_socketio import SocketIO,emit,join_room,leave_room,send

from werkzeug import secure_filename



app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio=SocketIO(app)



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


@app.route("/chat" ,methods=["POST"])
def chat():
    print("running chat")
    return render_template("chat.html")


@socketio.on('join')
def on_join(data):
    username = data['user']
    room = data['room']
    join_room(room)
    emit('chat',{'username':username},room=room)
    print("room has been allocated")

当我只在没有socketio的情况下执行url_for时,我能够更改路由,但现在似乎不起作用。在控制台和cmd中,我能够看到socketio正常工作,但是聊天路线不正常

0 个答案:

没有答案