【问题标题】:Flask server not starting for SocketIOFlask 服务器没有为 SocketIO 启动
【发布时间】:2020-04-25 12:23:12
【问题描述】:

我正在尝试使用 SocketIO 制作一个聊天应用程序并关注此视频:https://www.youtube.com/watch?v=RdSrkkrj3l4 和相应的 GitHub 代码:https://github.com/PrettyPrinted/flask-socketio-chat

这个文件是我的main.py 文件

from flask_socketio import SocketIO

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
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)

这是我的 index.html 页面

<html>
<head>
<title>Chat Room</title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.4.8/socket.io.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function() {

    var socket = io.connect('http://127.0.0.1:5000');

    socket.on('connect', function() {
        socket.send('User has connected!');
    });

    socket.on('message', function(msg) {
        $("#messages").append('<li>'+msg+'</li>');
        console.log('Received message');
    });

    $('#sendbutton').on('click', function() {
        socket.send($('#myMessage').val());
        $('#myMessage').val('');
    });

});
</script>
<ul id="messages"></ul>
<input type="text" id="myMessage">
<button id="sendbutton">Send</button>
</body>
</html>

但是,当我使用 python main.py 运行烧瓶代码时。它从不加载任何东西,只是显示:

Output screenshot

C:\Users\Harshit Parikh\Desktop\app>python main.py

请帮帮我。

【问题讨论】:

  • 嗯,看来你的代码没问题,尝试检查你的网络权限,或者尝试使用app.run() insted socketio.run(app) 启动服务器,看看问题出在flask 还是只有socketIO 跨度>

标签: javascript python html flask socket.io


【解决方案1】:

在使用虚拟环境并再次安装所有库时它工作正常。

【讨论】:

    【解决方案2】:

    我使用 app.run() 而不是 socketio.run(app),就像问题下方评论中建议的 Caio 一样。这对我有用。

    启动后,我切换回socketio.run,我的应用程序仍然有效。也许socketio需要某种kickstart?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-25
      • 2018-01-19
      • 1970-01-01
      • 2015-02-13
      • 2014-02-09
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多