提交 | 用户 | 时间
|
71e81e
|
1 |
<!DOCTYPE html> |
懒 |
2 |
<html> |
|
3 |
|
|
4 |
<head> |
|
5 |
<meta charset="utf-8"> |
|
6 |
<title>Java后端WebSocket的Tomcat实现</title> |
|
7 |
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> |
|
8 |
</head> |
|
9 |
|
|
10 |
<body> |
|
11 |
<div id="main" style="width: 1200px;height:800px;"></div> |
|
12 |
Welcome<br/><input id="text" type="text" /> |
|
13 |
<button onclick="send()">发送消息</button> |
|
14 |
<hr/> |
|
15 |
<button onclick="closeWebSocket()">关闭WebSocket连接</button> |
|
16 |
<hr/> |
|
17 |
<div id="message"></div> |
|
18 |
</body> |
|
19 |
<script type="text/javascript"> |
|
20 |
var websocket = null; |
|
21 |
//判断当前浏览器是否支持WebSocket |
|
22 |
if('WebSocket' in window) { |
|
23 |
//改成你的地址 |
|
24 |
websocket = new WebSocket('ws://127.0.0.1:8081/websocket/badao'); |
|
25 |
} else { |
|
26 |
alert('当前浏览器 Not support websocket') |
|
27 |
} |
|
28 |
|
|
29 |
//连接发生错误的回调方法 |
|
30 |
websocket.onerror = function() { |
|
31 |
setMessageInnerHTML("WebSocket连接发生错误"); |
|
32 |
}; |
|
33 |
|
|
34 |
//连接成功建立的回调方法 |
|
35 |
websocket.onopen = function() { |
|
36 |
setMessageInnerHTML("WebSocket连接成功"); |
|
37 |
} |
|
38 |
var U01data, Uidata, Usdata |
|
39 |
//接收到消息的回调方法 |
|
40 |
websocket.onmessage = function(event) { |
|
41 |
console.log(event); |
|
42 |
console.log(event.data) |
|
43 |
setMessageInnerHTML(event); |
|
44 |
} |
|
45 |
|
|
46 |
//连接关闭的回调方法 |
|
47 |
websocket.onclose = function() { |
|
48 |
setMessageInnerHTML("WebSocket连接关闭"); |
|
49 |
} |
|
50 |
|
|
51 |
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 |
|
52 |
window.onbeforeunload = function() { |
|
53 |
closeWebSocket(); |
|
54 |
} |
|
55 |
|
|
56 |
//将消息显示在网页上 |
|
57 |
function setMessageInnerHTML(innerHTML) { |
|
58 |
document.getElementById('message').innerHTML += innerHTML + '<br/>'; |
|
59 |
} |
|
60 |
|
|
61 |
//关闭WebSocket连接 |
|
62 |
function closeWebSocket() { |
|
63 |
websocket.close(); |
|
64 |
} |
|
65 |
|
|
66 |
//发送消息 |
|
67 |
function send() { |
|
68 |
var message = document.getElementById('text').value; |
|
69 |
websocket.send('{"msg":"' + message + '"}'); |
|
70 |
setMessageInnerHTML(message + " "); |
|
71 |
} |
|
72 |
</script> |
|
73 |
|
|
74 |
</html> |