test.html
2.81 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket test</title>
<style>
p { padding: 0; margin: 0; }
.container{ margin: 10vh auto; width: 40%; border: 1px solid #ffeeaa; padding: 10px; }
#output { max-height: 500px; margin-bottom: 10px; overflow-y: auto; }
.message-wrapper { width: 100%; overflow: hidden; }
.message-wrapper input { float: left; width: 90%; padding: 4px 12px; box-sizing: border-box; }
.message-wrapper button { float: right; padding: 4px 10px; }
</style>
</head>
<body>
<div class="container">
<div id="output"></div>
<div class="message-wrapper">
<input type="text" id="msg" />
<button id="sendBtn">发 送</button>
</div>
</div>
<script src="./js/socket.js"></script>
<script>
if (!window.WebSocket) {
//
}
var socket = new ws('ws://123.207.136.134:9010/ajaxchattest'),
str = 'Hello WebSocket!!';
socket.onconnecting = function (ev) {
console.log('socket:onconnecting', ev)
sendMsg('socket test...')
}
socket.onopen = function(ev) {
console.log('socket:onopen', ev)
log('发了个消息!' + str)
sendMsg(str)
}
socket.onclose = function(ev) {
console.log('socket:onclose', ev)
log('WebSocket Closed!!')
}
socket.onmessage = function(ev) {
console.log('socket:onmessage', ev)
log('收到消息 ' + ev.data)
// socket.close()
}
var sendBtn = document.getElementById('sendBtn'),
msgInput = document.getElementById('msg');
sendBtn.onclick = onBtnClick
function onBtnClick() {
var val = msgInput.value.trim();
if (!val) return
sendMsg(val)
msgInput.value = ''
}
document.addEventListener('keydown', function(ev) {
var e = ev || window.event;
if (e.keyCode === 13) {
onBtnClick()
}
})
function sendMsg(str) {
console.log('socket:sendMsg', str)
socket.send(str)
}
var timer = null
function log(s, e) {
var output = document.getElementById('output'),
p = document.createElement('p');
clearTimeout(timer);
timer = null
p.style.wordWrap = 'break-word';
p.style.padding = '10px';
p.style.marginBottom = '4px';
p.style.background = '#eee';
p.textContent = 'LOG : ' + s;
// 往上追加
// output.childNodes.length
// ? output.insertBefore(p, output.childNodes[0])
// : output.appendChild(p);
// 往下追加
output.appendChild(p);
if (output.offsetWidth !== output.scrollWidth) {
console.log('timer', timer)
output.scrollTop = output.scrollHeight
timer = setTimeout(function() {
}, 100)
}
}
</script>
</body>
</html>