以下是一个简单的HTML页面,它包含一个输入框、一个发送按钮和一个显示区域。用户可以在输入框中输入消息,点击发送按钮,然后这个消息会被发送到 Flask-SocketIO 服务器。当服务器回应消息时,它会在页面的显示区域显示出来。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Flask-SocketIO Chat</title>
<!-- Import the Socket.IO client library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script>
<script type="text/javascript">
document.addEventListener("DOMContentLoaded", function() {
const socket = io.connect('http://localhost:5000');
const messagesDiv = document.getElementById('messages');
const inputElem = document.getElementById('messageInput');
const buttonElem = document.getElementById('sendButton');
// Listen for a 'response' event from the server
socket.on('response', function(msg) {
const pElem = document.createElement('p');
pElem.innerText = msg.data;
messagesDiv.appendChild(pElem);
});
// Send the input message to the server on button click
buttonElem.addEventListener('click', function() {
const message = inputElem.value;
socket.emit('send_message', {data: message});
inputElem.value = ''; // Clear the input
});
});
</script>
</head>
<body>
<h1>Flask-SocketIO Chat</h1>
<input type="text" id="messageInput" placeholder="Type your message here...">
<button id="sendButton">Send</button>
<div id="messages"></div>
</body>
</html>
此外,Flask-SocketIO 服务器端代码可以处理客户端发送的 send_message
事件,并返回一个 response
事件。例如:文章来源:https://www.toymoban.com/news/detail-671702.html
from flask import Flask
from flask_socketio import SocketIO
app = Flask(__name__)
socketio = SocketIO(app)
@socketio.on('send_message')
def handle_message(message):
print('Received message:', message['data'])
socketio.emit('response', {'data': 'Server received: ' + message['data']})
if __name__ == '__main__':
socketio.run(app, debug=True)
当用户在HTML页面上输入消息并点击发送按钮时,消息会被发送到 Flask-SocketIO 服务器。服务器接收到消息后,会发送一个回应,该回应将在页面上显示。文章来源地址https://www.toymoban.com/news/detail-671702.html
到了这里,关于html写一个向flask_socketio发送消息和接收消息并显示在页面上的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!