最近一個(gè)項(xiàng)目中,需要用到Java的websocket新特性,于是就學(xué)了一下,感覺(jué)這技術(shù)還挺好玩的,瞬間知道網(wǎng)頁(yè)上面的那些在線客服是怎么做的了。
先看圖:
實(shí)現(xiàn)了多客戶(hù)機(jī)進(jìn)行實(shí)時(shí)通訊。
下面看代碼項(xiàng)目結(jié)構(gòu)圖:很簡(jiǎn)單,就1個(gè)類(lèi),1個(gè)頁(yè)面
然后看具體代碼
先看后端代碼
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
104
|
package com.main; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; import javax.websocket.*; import javax.websocket.server.ServerEndpoint; /** * @ServerEndpoint 注解是一個(gè)類(lèi)層次的注解,它的功能主要是將目前的類(lèi)定義成一個(gè)websocket服務(wù)器端, * 注解的值將被用于監(jiān)聽(tīng)用戶(hù)連接的終端訪問(wèn)URL地址,客戶(hù)端可以通過(guò)這個(gè)URL來(lái)連接到WebSocket服務(wù)器端 */ @ServerEndpoint ( "/websocket" ) public class H5ServletServerSocket { // 靜態(tài)變量,用來(lái)記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。 private static int onlineCount = 0 ; // concurrent包的線程安全Set,用來(lái)存放每個(gè)客戶(hù)端對(duì)應(yīng)的MyWebSocket對(duì)象。若要實(shí)現(xiàn)服務(wù)端與單一客戶(hù)端通信的話(huà),可以使用Map來(lái)存放,其中Key可以為用戶(hù)標(biāo)識(shí) private static CopyOnWriteArraySet<H5ServletServerSocket> webSocketSet = new CopyOnWriteArraySet<H5ServletServerSocket>(); // 與某個(gè)客戶(hù)端的連接會(huì)話(huà),需要通過(guò)它來(lái)給客戶(hù)端發(fā)送數(shù)據(jù) private Session session; /** * 連接建立成功調(diào)用的方法 * * @param session * 可選的參數(shù)。session為與某個(gè)客戶(hù)端的連接會(huì)話(huà),需要通過(guò)它來(lái)給客戶(hù)端發(fā)送數(shù)據(jù) */ @OnOpen public void onOpen(Session session) { this .session = session; webSocketSet.add( this ); // 加入set中 addOnlineCount(); // 在線數(shù)加1 System.out.println( "有新連接加入!當(dāng)前在線人數(shù)為" + getOnlineCount()); } /** * 連接關(guān)閉調(diào)用的方法 */ @OnClose public void onClose() { webSocketSet.remove( this ); // 從set中刪除 subOnlineCount(); // 在線數(shù)減1 System.out.println( "有一連接關(guān)閉!當(dāng)前在線人數(shù)為" + getOnlineCount()); } /** * 收到客戶(hù)端消息后調(diào)用的方法 * * @param message * 客戶(hù)端發(fā)送過(guò)來(lái)的消息 * @param session * 可選的參數(shù) */ @OnMessage public void onMessage(String message, Session session) { System.out.println( "來(lái)自客戶(hù)端的消息:" + message); // 群發(fā)消息 for (H5ServletServerSocket item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { e.printStackTrace(); continue ; } } } /** * 發(fā)生錯(cuò)誤時(shí)調(diào)用 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { System.out.println( "發(fā)生錯(cuò)誤" ); error.printStackTrace(); } /** * 這個(gè)方法與上面幾個(gè)方法不一樣。沒(méi)有用注解,是根據(jù)自己需要添加的方法。 * * @param message * @throws IOException */ public void sendMessage(String message) throws IOException { this .session.getBasicRemote().sendText(message); // this.session.getAsyncRemote().sendText(message); } public static synchronized int getOnlineCount() { return onlineCount; } public static synchronized void addOnlineCount() { H5ServletServerSocket.onlineCount++; } public static synchronized void subOnlineCount() { H5ServletServerSocket.onlineCount--; } } |
接下來(lái)是前端頁(yè)面代碼:
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
|
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML> < html > < head > < base href="<%=basePath%>"> < title >My WebSocket</ title > </ head > < body > 歡迎進(jìn)入聊天室 < div id = "message" style = "color: blue" >【狀態(tài)】</ div > < br /> 昵稱(chēng) < input id = "username" type = "text" required = "required" /> < br > 內(nèi)容 < input id = "text" type = "text" /> < br /> < button onclick = "send()" >發(fā)送</ button > < button onclick = "closeWebSocket()" >關(guān)閉</ button > </ body > < script type = "text/javascript" > var websocket = null; //判斷當(dāng)前瀏覽器是否支持WebSocket if ('WebSocket' in window) { websocket = new WebSocket("ws://10.1.1.106:8080/Socket/websocket"); } else { alert('不支持WebSocket!') } //連接發(fā)生錯(cuò)誤的回調(diào)方法 websocket.onerror = function() { setMessageInnerHTML("error"); }; //連接成功建立的回調(diào)方法 websocket.onopen = function(event) { setMessageInnerHTML("聊天室開(kāi)啟"); } //接收到消息的回調(diào)方法 websocket.onmessage = function() { setMessageInnerHTML(event.data); } //連接關(guān)閉的回調(diào)方法 websocket.onclose = function() { setMessageInnerHTML("聊天室關(guān)閉"); } //監(jiān)聽(tīng)窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒(méi)斷開(kāi)就關(guān)閉窗口,server端會(huì)拋異常。 window.onbeforeunload = function() { websocket.close(); } //將消息顯示在網(wǎng)頁(yè)上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '< br />'; } //關(guān)閉連接 function closeWebSocket() { websocket.close(); } //發(fā)送消息 function send() { var username = document.getElementById('username').value; var message = document.getElementById('text').value; var msg = "【" + username + "】發(fā)言:" + message websocket.send(msg); } </ script > </ html > |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。