Flask-SocketIO连接问题

时间:2019-12-13 10:56:45

标签: python flask

我在使用Flask-SocketIO时遇到问题

当我单击运行Flask服务器时给出的链接时,我希望我的HTML页面呈现“用户已连接客户端”

以下是代码:

application.py


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

from flask import render_template

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


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


@socketio.on('connect')
def connect():
    print("An user has connected Server Side")


@socketio.on('joined')
def joined():
    emit('user-connect', {'msg': 'User has connected Client Side'})


@socketio.on('disconnect')
def disconnect():
    print('User disconnected')


if __name__ == '__main__':
    # app.run(host='127.0.0.1', port='8080', debug=True)
    socketio.run(app)

static / index.js

document.addEventListener("DOMContentLoaded", () => {


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

  // When connected, configure button
  socket.on('connect', () => {
    socket.emit('joined');
  });

  socket.on('user-connect', data => {
    const p = document.createElement('p')
    p.innerHTML = `${data.msg}`
    document.querySelector('#log').append(p);
  });

});

templates / index.html

<html>
  <head>
    <!-- Javascript -->
    <script src="{{ url_for('static', filename='index.js') }}"></script>

    <!-- SocketIO -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js" integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I=" crossorigin="anonymous"></script>


    <title>Chatroom</title>
    <meta charset="utf-8" />

  </head>
  <body>
    <h1>INDEX PAGE</h1>

    <h2>Receive:</h2>
    <div id="log"></div>




  </body>
</html>

这是我在HTML页面上获得的当前渲染

HTML-rendering

任何帮助将不胜感激..谢谢


这是我运行pip list时得到的信息

Package         Version
--------------- -------
Click           7.0    
dnspython       1.16.0 
eventlet        0.25.1 
Flask           1.1.1  
Flask-SocketIO  4.2.1  
greenlet        0.4.15 
itsdangerous    1.1.0  
Jinja2          2.10.3 
MarkupSafe      1.1.1  
monotonic       1.5    
pip             19.3.1 
python-engineio 3.11.1 
python-socketio 4.4.0  
setuptools      42.0.2 
six             1.13.0 
Werkzeug        0.16.0 
wheel           0.33.6 

这是我文件的PATH

project2/
├── application.py
├── requirements.txt
├── static
│   ├── index.js
│   └── index.js~
└── templates
    ├── index.html
    └── index.html~

1 个答案:

答案 0 :(得分:0)

您安装了Flask和Flask-SocketIO吗?

您添加了以下行:     import os 到您的application.py?

添加这些代码后,您的代码对我有用。