一、介紹
1.兩種方式,一種使用tomcat的websocket實現,一種使用spring的websocket
2.tomcat的方式需要tomcat 7.x,jee7的支持。
3.spring與websocket整合需要spring 4.x,并且使用了socketjs,對不支持websocket的瀏覽器可以模擬websocket使用
二、方式一:tomcat
使用這種方式無需別的任何配置,只需服務端一個處理類,
服務器端代碼
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
|
package com.socket; import java.io.ioexception; import java.util.map; import java.util.concurrent.concurrenthashmap; import javax.websocket.*; import javax.websocket.server.pathparam; import javax.websocket.server.serverendpoint; import net.sf.json.jsonobject; @serverendpoint ( "/websocket/{username}" ) public class websocket { private static int onlinecount = 0 ; private static map<string, websocket> clients = new concurrenthashmap<string, websocket>(); private session session; private string username; @onopen public void onopen( @pathparam ( "username" ) string username, session session) throws ioexception { this .username = username; this .session = session; addonlinecount(); clients.put(username, this ); system.out.println( "已連接" ); } @onclose public void onclose() throws ioexception { clients.remove(username); subonlinecount(); } @onmessage public void onmessage(string message) throws ioexception { jsonobject jsonto = jsonobject.fromobject(message); if (!jsonto.get( "to" ).equals( "all" )){ sendmessageto( "給一個人" , jsonto.get( "to" ).tostring()); } else { sendmessageall( "給所有人" ); } } @onerror public void onerror(session session, throwable error) { error.printstacktrace(); } public void sendmessageto(string message, string to) throws ioexception { // session.getbasicremote().sendtext(message); //session.getasyncremote().sendtext(message); for (websocket item : clients.values()) { if (item.username.equals(to) ) item.session.getasyncremote().sendtext(message); } } public void sendmessageall(string message) throws ioexception { for (websocket item : clients.values()) { item.session.getasyncremote().sendtext(message); } } public static synchronized int getonlinecount() { return onlinecount; } public static synchronized void addonlinecount() { websocket.onlinecount++; } public static synchronized void subonlinecount() { websocket.onlinecount--; } public static synchronized map<string, websocket> getclients() { return clients; } } |
客戶端js
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
|
var websocket = null ; var username = localstorage.getitem( "name" ); //判斷當前瀏覽器是否支持websocket if ( 'websocket' in window) { websocket = new websocket( "ws://" + document.location.host + "/webchat/websocket/" + username + "/" + _img); } else { alert( '當前瀏覽器 not support websocket' ) } //連接發生錯誤的回調方法 websocket.onerror = function() { setmessageinnerhtml( "websocket連接發生錯誤" ); }; //連接成功建立的回調方法 websocket.onopen = function() { setmessageinnerhtml( "websocket連接成功" ); } //接收到消息的回調方法 websocket.onmessage = function(event) { setmessageinnerhtml(event.data); } //連接關閉的回調方法 websocket.onclose = function() { setmessageinnerhtml( "websocket連接關閉" ); } //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。 window.onbeforeunload = function() { closewebsocket(); } //關閉websocket連接 function closewebsocket() { websocket.close(); } |
發送消息只需要使用websocket.send(“發送消息”),就可以觸發服務端的onmessage()方法,當連接時,觸發服務器端onopen()方法,此時也可以調用發送消息的方法去發送消息。關閉websocket時,觸發服務器端onclose()方法,此時也可以發送消息,但是不能發送給自己,因為自己的已經關閉了連接,但是可以發送給其他人。
三、方法二:spring整合
websocketconfig.java
這個類是配置類,所以需要在spring mvc配置文件中加入對這個類的掃描,第一個addhandler是對正常連接的配置,第二個是如果瀏覽器不支持websocket,使用socketjs模擬websocket的連接。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
package com.websocket; import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.web.socket.config.annotation.enablewebsocket; import org.springframework.web.socket.config.annotation.websocketconfigurer; import org.springframework.web.socket.config.annotation.websockethandlerregistry; import org.springframework.web.socket.handler.textwebsockethandler; @configuration @enablewebsocket public class websocketconfig implements websocketconfigurer { @override public void registerwebsockethandlers(websockethandlerregistry registry) { registry.addhandler(chatmessagehandler(), "/websocketserver" ).addinterceptors( new chathandshakeinterceptor()); registry.addhandler(chatmessagehandler(), "/sockjs/websocketserver" ).addinterceptors( new chathandshakeinterceptor()).withsockjs(); } @bean public textwebsockethandler chatmessagehandler(){ return new chatmessagehandler(); } } |
chathandshakeinterceptor.java
這個類的作用就是在連接成功前和成功后增加一些額外的功能,constants.java類是一個工具類,兩個常量。
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
|
package com.websocket; import java.util.map; import org.apache.shiro.securityutils; import org.springframework.http.server.serverhttprequest; import org.springframework.http.server.serverhttpresponse; import org.springframework.web.socket.websockethandler; import org.springframework.web.socket.server.support.httpsessionhandshakeinterceptor; public class chathandshakeinterceptor extends httpsessionhandshakeinterceptor { @override public boolean beforehandshake(serverhttprequest request, serverhttpresponse response, websockethandler wshandler, map<string, object> attributes) throws exception { system.out.println( "before handshake" ); /* * if (request instanceof servletserverhttprequest) { * servletserverhttprequest servletrequest = (servletserverhttprequest) * request; httpsession session = * servletrequest.getservletrequest().getsession(false); if (session != * null) { //使用username區分websockethandler,以便定向發送消息 string username = * (string) session.getattribute(constants.session_username); if * (username==null) { username="default-system"; } * attributes.put(constants.websocket_username,username); * * } } */ //使用username區分websockethandler,以便定向發送消息(使用shiro獲取session,或是使用上面的方式) string username = (string) securityutils.getsubject().getsession().getattribute(constants.session_username); if (username == null ) { username = "default-system" ; } attributes.put(constants.websocket_username, username); return super .beforehandshake(request, response, wshandler, attributes); } @override public void afterhandshake(serverhttprequest request, serverhttpresponse response, websockethandler wshandler, exception ex) { system.out.println( "after handshake" ); super .afterhandshake(request, response, wshandler, ex); } } |
chatmessagehandler.java
這個類是對消息的一些處理,比如是發給一個人,還是發給所有人,并且前端連接時觸發的一些動作
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
|
package com.websocket; import java.io.ioexception; import java.util.arraylist; import org.apache.log4j.logger; import org.springframework.web.socket.closestatus; import org.springframework.web.socket.textmessage; import org.springframework.web.socket.websocketsession; import org.springframework.web.socket.handler.textwebsockethandler; public class chatmessagehandler extends textwebsockethandler { private static final arraylist<websocketsession> users; // 這個會出現性能問題,最好用map來存儲,key用userid private static logger logger = logger.getlogger(chatmessagehandler. class ); static { users = new arraylist<websocketsession>(); } /** * 連接成功時候,會觸發ui上onopen方法 */ @override public void afterconnectionestablished(websocketsession session) throws exception { system.out.println( "connect to the websocket success......" ); users.add(session); // 這塊會實現自己業務,比如,當用戶登錄后,會把離線消息推送給用戶 // textmessage returnmessage = new textmessage("你將收到的離線"); // session.sendmessage(returnmessage); } /** * 在ui在用js調用websocket.send()時候,會調用該方法 */ @override protected void handletextmessage(websocketsession session, textmessage message) throws exception { sendmessagetousers(message); //super.handletextmessage(session, message); } /** * 給某個用戶發送消息 * * @param username * @param message */ public void sendmessagetouser(string username, textmessage message) { for (websocketsession user : users) { if (user.getattributes().get(constants.websocket_username).equals(username)) { try { if (user.isopen()) { user.sendmessage(message); } } catch (ioexception e) { e.printstacktrace(); } break ; } } } /** * 給所有在線用戶發送消息 * * @param message */ public void sendmessagetousers(textmessage message) { for (websocketsession user : users) { try { if (user.isopen()) { user.sendmessage(message); } } catch (ioexception e) { e.printstacktrace(); } } } @override public void handletransporterror(websocketsession session, throwable exception) throws exception { if (session.isopen()) { session.close(); } logger.debug( "websocket connection closed......" ); users.remove(session); } @override public void afterconnectionclosed(websocketsession session, closestatus closestatus) throws exception { logger.debug( "websocket connection closed......" ); users.remove(session); } @override public boolean supportspartialmessages() { return false ; } } |
spring-mvc.xml
正常的配置文件,同時需要增加對websocketconfig.java類的掃描,并且增加
1
2
3
|
xmlns:websocket= "http://www.springframework.org/schema/websocket" http: //www.springframework.org/schema/websocket <a target= "_blank" href= "http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd" rel= "external nofollow" >http://www.springframework.org/schema/websocket/spring-websocket- 4.1 .xsd</a> |
客戶端
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
|
<script type= "text/javascript" src= "http://localhost:8080/bank/js/sockjs-0.3.min.js" ></script> <script> var websocket; if ( 'websocket' in window) { websocket = new websocket( "ws://" + document.location.host + "/bank/websocketserver" ); } else if ( 'mozwebsocket' in window) { websocket = new mozwebsocket( "ws://" + document.location.host + "/bank/websocketserver" ); } else { websocket = new sockjs( "http://" + document.location.host + "/bank/sockjs/websocketserver" ); } websocket.onopen = function(evnt) {}; websocket.onmessage = function(evnt) { $( "#test" ).html( "(<font color='red'>" + evnt.data + "</font>)" ) }; websocket.onerror = function(evnt) {}; websocket.onclose = function(evnt) {} $( '#btn' ).on( 'click' , function() { if (websocket.readystate == websocket.open) { var msg = $( '#id' ).val(); //調用后臺handletextmessage方法 websocket.send(msg); } else { alert( "連接失敗!" ); } }); </script> |
注意導入socketjs時要使用地址全稱,并且連接使用的是http而不是websocket的ws
總結
以上所述是小編給大家介紹的java 實現websocket的兩種方式實例詳解,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://blog.csdn.net/sinat_23324343/article/details/81237973