-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocket.html
More file actions
82 lines (77 loc) · 2.86 KB
/
Socket.html
File metadata and controls
82 lines (77 loc) · 2.86 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>客户端对象</title>
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
<script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</head>
<body>
<div class="well well-sm">当前用户数:
<b id="PeopleNum" style="color: darkcyan">0</b>
</div>
<div id="msg"></div>
<input type="text" id="text">
<input type="submit" value="发送数据" onclick="song()">
</body>
<script>
//注册键盘事件
document.onkeydown = function(e) {
//捕捉回车事件
var ev = (typeof event!= 'undefined') ? window.event : e;
if(ev.keyCode == 13) {
song();
}
};
var msg = document.getElementById("msg");
var PeopleNum = document.getElementById("PeopleNum");
var wsServer = 'ws://100.100.0.223:9502';
//调用websocket对象建立连接:
//参数:ws/wss(加密)://ip:port (字符串)
var websocket = new WebSocket(wsServer);
//onopen监听连接打开
websocket.onopen = function (evt) {
//websocket.readyState 属性:
/*
CONNECTING 0 The connection is not yet open.
OPEN 1 The connection is open and ready to communicate.
CLOSING 2 The connection is in the process of closing.
CLOSED 3 The connection is closed or couldn't be opened.
*/
if(websocket.readyState == 1){
msg.innerHTML = "链接已建立!<br/>"
}else{
msg.innerHTML = "Something is Wrong !<br/>";
}
// msg.innerHTML = websocket.readyState;
};
function song(){
var text = document.getElementById('text').value;
document.getElementById('text').value = '';
//向服务器发送数据
websocket.send(text);
}
//监听连接关闭
// websocket.onclose = function (evt) {
// console.log("Disconnected");
// };
//onmessage 监听服务器数据推送
websocket.onmessage = function (evt) {
var jsonData = JSON.parse(evt.data);
console.log(jsonData);
console.log(jsonData.text);
if(jsonData.text){
msg.innerHTML += jsonData.text +'<br>';
}else{
PeopleNum.innerHTML = jsonData.ppp ;
}
// console.log('Retrieved data from server: ' + evt.data);
};
//监听连接错误信息
// websocket.onerror = function (evt, e) {
// console.log('Error occured: ' + evt.data);
// };
</script>
</html>