websockets/examples/simple-example.html

41 lines
1022 B
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<title>Simple Websocket Example</title>
<style>
#output {
width: 100%;
height: 500px;
font-family: monospace;
}
</style>
</head>
<body>
<h1>Simple Websocket Example</h1>
<textarea id="output"></textarea>
<script>
const output = document.getElementById('output');
window.onload = () => {
output.value = '';
}
const ws = new WebSocket('ws://localhost:8080/ws');
ws.onopen = () => {
output.value += 'WebSocket connection opened.\n';
ws.send('Hello, server!');
};
ws.onmessage = (event) => {
output.value += `Message from server: ${event.data}\n`;
};
ws.onclose = () => {
output.value += 'WebSocket connection closed.\n';
};
ws.onerror = (error) => {
output.value += `WebSocket error: ${error.message}\n`;
};
</script>
</body>
</html>