-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathclient.html
96 lines (83 loc) · 3.44 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<html>
<head>
<title>ws</title>
</head>
<body>
<div class="container">
<center>
<h1>ws </h1>
</center>
<button onclick="Conn()">链接</button>
<input id="url" type="text" value="ws://abc.com:8080/api/v1/ws" /> 发送人:
<input id="username" type="text" /> 内容:
<input id="text" type="text" style="width:300px" />
<button onclick="send()">发送</button>
<button onclick="closeWebSocket()">断开</button>
<div id="message"></div>
</div>
</body>
<script type="text/javascript">
var websocket = null;
function Conn() {
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket(document.getElementById('url').value);
} else {
alert('您的浏览器不支持 websocket!');
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("error");
};
//连接成功建立的回调方法
websocket.onopen = function (event) {
alert("链接成功,欢迎使用websocket!");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
var username = document.getElementById('username').value;
setMessageInnerHTML(getNowFormatDate() + " " + username + " 断开了链接!");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
websocket.close();
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
}
//关闭连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var username = document.getElementById('username').value;
var message = document.getElementById('text').value;
websocket.send(getNowFormatDate() + " " + username + "发送: " + message + "<br/>");
//发送消息后,发送消息框自动清空
document.getElementById('text').value = "";
}
function getNowFormatDate() {
var myDate = new Date();
myDate.getYear(); //获取当前年份(2位)
myDate.getFullYear(); //获取完整的年份(4位,1970-????)
myDate.getMonth(); //获取当前月份(0-11,0代表1月)
myDate.getDate(); //获取当前日(1-31)
myDate.getDay(); //获取当前星期X(0-6,0代表星期天)
myDate.getTime(); //获取当前时间(从1970.1.1开始的毫秒数)
myDate.getHours(); //获取当前小时数(0-23)
myDate.getMinutes(); //获取当前分钟数(0-59)
myDate.getSeconds(); //获取当前秒数(0-59)
myDate.getMilliseconds(); //获取当前毫秒数(0-999)
myDate.toLocaleDateString(); //获取当前日期
var mytime = myDate.toLocaleTimeString(); //获取当前时间
return myDate.toLocaleString(); //获取日期与时间
}
</script>
</html>