Files
gitea-pages/examples/js_ws/index.html
2026-01-29 14:18:08 +08:00

82 lines
2.7 KiB
HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple WebSocket Example</title>
</head>
<body>
<h1>Simple WebSocket Echo</h1>
<div id="status">Disconnected</div>
<div id="messages" style="border: 1px solid #ccc; height: 300px; overflow-y: scroll; padding: 10px; margin-bottom: 10px;"></div>
<input type="text" id="input" placeholder="Type a message...">
<button onclick="send()">Send</button>
<button onclick="connect()">Connect</button>
<button onclick="disconnect()">Disconnect</button>
<script>
let ws;
const statusDiv = document.getElementById('status');
const messagesDiv = document.getElementById('messages');
const input = document.getElementById('input');
function connect() {
if (ws) return;
// Get the current host (including port)
const host = window.location.host;
// Determine the protocol (ws or wss) based on the current page protocol
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
// Construct the WebSocket URL. Note the leading slash for absolute path.
// Since .pages.yaml maps "ws" to the JS handler, we connect to /ws
const wsUrl = `${protocol}//${host}/ws`;
console.log('Connecting to:', wsUrl); // Debug log
ws = new WebSocket(wsUrl);
ws.onopen = () => {
statusDiv.innerText = 'Connected';
log('Connected to ' + wsUrl);
};
ws.onmessage = (event) => {
log('Received: ' + event.data);
};
ws.onclose = () => {
statusDiv.innerText = 'Disconnected';
log('Disconnected');
ws = null;
};
ws.onerror = (error) => {
statusDiv.innerText = 'Error';
log('Error: ' + error);
};
}
function disconnect() {
if (ws) {
ws.close();
}
}
function send() {
if (ws && ws.readyState === WebSocket.OPEN) {
const msg = input.value;
ws.send(msg);
log('Sent: ' + msg);
input.value = '';
} else {
alert('Not connected');
}
}
function log(msg) {
const div = document.createElement('div');
div.innerText = msg;
messagesDiv.appendChild(div);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
</script>
</body>
</html>