Mychat-Flask-SocketIO简易聊天室

时间:2021-12-04  打赏:9.9元

方案一:

核心代码:

from flask import Flask, render_template
from flask_socketio import SocketIO
from werkzeug import debug
import os

import gevent

app = Flask(__name__)

app.secret_key = os.environ.get("SECRET_KEY")

socketio = SocketIO(app)

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


@socketio.on('message')
def handle_message(data):
    print('received message: ' + data)
    socketio.emit('updateui', data)

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

方案二:

核心代码:

@socketio.on("message")
def message(data):
    message = data["message"]
    username = data["username"]
    timestamp = time.strftime('%b-%d %I:%M%p', time.localtime())
    channel = data["channel"]
    msg = [channel.strip(), username, message, timestamp]
    # print(msg)
    if len(messageList) < 200:
        messageList.append(msg)
    else:
        messageList.append(msg)
        messageList.remove(messageList[0])
    emit("show message", {"message": message, "username": username, 
                "timestamp": timestamp, "channel": channel}, broadcast=True)