在Flask中用python做个内网网页聊天应用,端口5000
python代码
from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)
@app.route('/')
def chat():
return render_template('chat.html')
@socketio.on('message')
def handle_message(data):
emit('message', {'message': data['message']}, broadcast=True)
if __name__ == '__main__':
socketio.run(app, debug=True)
chat.html
<!DOCTYPE html>
<html>
<head>
<title>Real-time Chat</title>
</head>
<body>
<h1>Real-time Chat</h1>
<ul id="chat">
</ul>
<input id="message_input" type="text" placeholder="Type a message...">
<button id="send_button">Send</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script>
var socket = io.connect('http://' + document.domain + ':' + location.port);
socket.on('message', function(data) {
var chat = document.getElementById('chat');
chat.innerHTML += '<li><strong>User ' + data.user_id + ':</strong> ' + data.message + '</li>';
});
document.getElementById('send_button').onclick = sendMessage;
document.getElementById('message_input').addEventListener('keypress', function(event) {
if (event.keyCode === 13) { // 检测是否按下回车键
sendMessage();
}
});
function sendMessage() {
var message = document.getElementById('message_input').value;
if (message.trim() !== '') { // 检测消息内容是否为空
socket.emit('message', {user_id: socket.id, message: message});
document.getElementById('message_input').value = '';
}
}
</script>
</body>监听回车直接发消息