-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathclient.html
74 lines (62 loc) · 1.58 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
63
64
65
66
67
68
69
70
71
72
73
74
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket client</title>
<style>
.container {
display: flex;
flex-direction: row;
}
.container > div {
margin-right: 2rem;
}
</style>
</head>
<body>
<div class="container">
<div><button id="connect">连接</button></div>
<div><button id="send">发送消息</button></div>
<div><button id="close">关闭连接</button></div>
</div>
<div id="append"></div>
<script>
var ws;
document.getElementById('connect').addEventListener('click',() => {
ws = new WebSocket('ws://127.0.0.1:6565')
ws.onopen = function(e){
console.log('onopen',e)
}
ws.onmessage = function(e){
let p = document.createElement('p')
p.innerHTML = e.data;
document.getElementById('append').appendChild(p)
}
ws.onclose = function(e){
console.log('onclose',e)
}
ws.onerror = function(e){
console.log('onerror',e)
}
})
document.getElementById('send').addEventListener('click',() => {
if(!ws){
console.error('请先连接');
return ;
}
let data = {
key: 'value',
now: Date.now()
}
ws.send(JSON.stringify(data))
})
document.getElementById('close').addEventListener('click',() => {
if(!ws){
console.error('请先连接');
return ;
}
ws.close()
})
</script>
</body>
</html>