以下是一個(gè)簡(jiǎn)單的HTML頁面,它包含一個(gè)輸入框、一個(gè)發(fā)送按鈕和一個(gè)顯示區(qū)域。用戶可以在輸入框中輸入消息,點(diǎn)擊發(fā)送按鈕,然后這個(gè)消息會(huì)被發(fā)送到 Flask-SocketIO 服務(wù)器。當(dāng)服務(wù)器回應(yīng)消息時(shí),它會(huì)在頁面的顯示區(qū)域顯示出來。
<!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>
此外,F(xiàn)lask-SocketIO 服務(wù)器端代碼可以處理客戶端發(fā)送的 send_message
事件,并返回一個(gè) response
事件。例如:文章來源:http://www.zghlxwxcb.cn/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)
當(dāng)用戶在HTML頁面上輸入消息并點(diǎn)擊發(fā)送按鈕時(shí),消息會(huì)被發(fā)送到 Flask-SocketIO 服務(wù)器。服務(wù)器接收到消息后,會(huì)發(fā)送一個(gè)回應(yīng),該回應(yīng)將在頁面上顯示。文章來源地址http://www.zghlxwxcb.cn/news/detail-671702.html
到了這里,關(guān)于html寫一個(gè)向flask_socketio發(fā)送消息和接收消息并顯示在頁面上的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!