-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.html
62 lines (53 loc) · 1.88 KB
/
client.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Client</title>
</head>
<body>
<h1>WebSocket Client Example</h1>
<div id="messages"></div>
<input type="text" id="inputMessage" placeholder="Enter a message">
<button id="sendButton">Send</button>
<script>
const messagesDiv = document.getElementById('messages');
const inputMessage = document.getElementById('inputMessage');
const sendButton = document.getElementById('sendButton');
const socket = new WebSocket("ws://localhost:8765/");
socket.onopen = (event) => {
console.log("Connected to server");
};
socket.onmessage = (event) => {
const message = event.data;
const messageElement = document.createElement('p');
messageElement.textContent = message;
messagesDiv.appendChild(messageElement);
};
socket.onclose = (event) => {
console.log("disconnected to server");
};
const isCmd = (s) => s.trim().startsWith('/')
let cmdId = 1
const send = () => {
const message = inputMessage.value;
if (message === '') return;
if (isCmd(message)) {
const [cmd, ...args] = message.split(' ')
payload = JSON.stringify({ id: cmdId, type: cmd.slice(1), args})
} else {
payload = JSON.stringify({type: "chat", message})
}
socket.send(payload);
inputMessage.value = '';
}
sendButton.addEventListener('click', send);
inputMessage.addEventListener('keydown', (e) => {
// console.log(e.code)
if (e.code === 'Enter') {
send()
}
}, false);
</script>
</body>
</html>