この記事では、SpringMVC統合WebSocketを共有して、参照のメッセージプッシュを実装しています。特定のコンテンツは次のとおりです
1. WebSocketハンドシェイクプロトコルの背景を作成します
(1)ハンドシェイクの実装クラス
/** *プロジェクト名:価格 *ファイル名:handshake.java *パッケージ名:com.yun.websocket *日付:2016年9月3日4:44:27 pm *Copyright(c)2016,[email protected] All rights reserved。 */パッケージcom.yun.websocket; java.util.mapをインポートします。 Import org.springframework.http.server.serverhttprequest; org.springframework.http.server.serverhttppresponseをインポートします。 Import org.springframework.http.server.servletserverhttprequest; Import org.springframework.web.socket.websockethandler; org.springframework.web.socket.server.handshakeInterceptorをインポートします。 /** *タイトル:ハンドシェイク<br/> *説明: *@company:qingdao litu hi-tech <br/> *@著者:liu yunsheng *@バージョン:v1.0 *@以来:JDK 1.7.0_80 *@日付:2016年9月3日4:44:27 PM事前に順調に(serverhttprequest request、serverhttpresponse応答、websockethandler wshandler、map <string、object>属性)例外{// todo auto-denerated method stub string jspcode =((servleteserverhttprequest)request)。 //タグユーザー// string userid =(string)session.getAttribute( "userId"); if(jspcode!= null){attributes.put( "jspcode"、jspcode); } else {return false; } trueを返します。 } @Override public void afterhandshake(serverhttprequest request、serverhtttpresponse応答、websockethandler wshandler、例外例外){// todo auto-feenated method stub}}}
(2)mywebsocketconfig実装クラス
/** *プロジェクト名:価格 *ファイル名:mywebsocketconfig.java *パッケージ名:com.yun.websocket *日付:2016年9月3日午後4時52分29時 *著作権(c)2016,[email protected]すべての権利予約。 */パッケージcom.yun.websocket; javax.annotation.resourceをインポートします。 org.springframework.stereotype.componentをインポートします。 Import org.springframework.web.servlet.config.annotation.enablewebmvc; Import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; org.springframework.web.socket.config.annotation.enablewebsocketをインポートします。 org.springframework.web.socket.config.annotation.websocketConfigurerをインポートします。 Import org.springframework.web.socket.config.annotation.websockethandlerregistry; /** *タイトル:mywebsocketconfig <br/> *説明: *@company:qingdao litu hi-tech <br/> *@著者:liu yunsheng *@バージョン:v1.0 *@@以来:jdk 1.7.0_80 *@日付:2016年9月3日4:52:29 pm mywebsocketconfigは、webmvcconfigureradapterを実装しているwebsocketconfigurer {@resource mywebsockethandlerハンドラーを実装しています。 @Override public void Registerwebsockethandlers(websockethandlerregistry registry){// todo auto-enerated method stub registry.addhandler( "/wsmy").addInterceptors(New Handshake()); registry.addhandler(handler、 "/wsmy/sockjs").addinterceptors(new handshake())。withsockjs(); }}
(3)mywebsockethandlerの実装クラス
/** *プロジェクト名:価格 *ファイル名:mywebsockethandler.java *パッケージ名:com.yun.websocket *日付:2016年9月3日午後4時55分12分 *著作権(c)2016,[email protected]すべての権利予約。 */パッケージcom.yun.websocket; java.io.ioexceptionをインポートします。 java.util.hashmapをインポートします。 java.util.iteratorをインポートします。 java.util.mapをインポートします。 java.util.map.entryをインポートします。 org.springframework.stereotype.componentをインポートします。 org.springframework.web.socket.closestatusをインポートします。 import org.springframework.web.socket.textmessage; Import org.springframework.web.socket.websockethandler; org.springframework.web.socket.websocketmessageをインポートします。 org.springframework.web.socket.websocketsessionをインポートします。 com.google.gson.gsonbuilderをインポートします。 /** *タイトル:mywebsockethandler <br/> *説明: *@company:qingdao litu hi-tech <br/> *@著者:liu yunsheng *@version:v1.0 *@@frus:@date:2016年9月3日4:55:12 pm静的最終マップ<String、websocketessession> usersocketsessionmap; static {usersocketsessionmap = new hashmap <string、websocketessession>(); } @Override public void afterconnectioneStabledished(websocketsession session)スロー例外{// todo auto-eneratedメソッドスタブstring jspcode =(string)session.gethandshakeattributes()。get( "jspcode"); if(usersocketsessionmap.get(jspcode)== null){usersocketsessionmap.put(jspcode、session); }(int i = 0; i <10; i ++){// broadcast(new gsonbuilder()。create()。tojson( "/" number/":/"+i+"/" "))); session.sendmessage(new Textmessage(new gsonbuilder()。create()。tojson( "/" number/":/"+i+"/" "))); }} @Override public void handlemessage(websocketessessionセッション、websocketmessage <?> message)スロー例外{// todo auto-enerated method stub // message messemsg = new gson()。 //msg.setdate(new date()); // sendmessagetouser(msg.getto()、new TextMessage(new gsonBuilder()。setDateFormat( "yyyy-mm-dd hh:mm:ss")。create()。tojson(msg))); session.sendmessage(メッセージ); } @Override public void handletransporterror(websocketessessionセッション、スロー可能な例外)スロー例外{// todo auto-fenated methood stub if(session.isopen()){session.close(); } iterator <entry <string、websocketessession >> it = usersocketsessionmap .entryset()。iterator(); //ソケットセッションを削除してください(it.hasnext()){entry <string、websocketsession> entry = it.next(); if(entry.getValue()。getId()。equals(session.getid())){usersocketsessionmap.remove(entry.getKey()); System.out.println( "ソケットセッションが削除されました:ユーザーID" + entry.getKey());壊す; }}} @Override public void afterconnectionclosed(websocketessession session、cordestatus coldestatus)をスローする{// todo auto-enerated method stub.out.println( "websocket:" + session.getid() + "close"); iterator <entry <string、websocketessession >> it = usersocketsessionmap.entryset()。iterator(); //ソケットセッションを削除してください(it.hasnext()){entry <string、websocketsession> entry = it.next(); if(entry.getValue()。getId()。equals(session.getid())){usersocketsessionmap.remove(entry.getKey()); System.out.println( "ソケットセッションが削除されました:ユーザーID" + entry.getKey());壊す; }}} / } / ** * bulk * @title:broadcast * @description:todo * @param:@param message * @param:@throws ioexception * @return:void * @author:liu yutheng * @date:4:23:30 pm on 2016年9月10日 * @throws * websocketessession >> it = usersocketsessionmap .entryset()。iterator(); //マルチスレッドマス送信while(it.hasnext()){final entry <string、websocketsession> entry = it.next(); if(entry.getValue()。isopen()){new Stread(new runnable(){public void run(){try {if(entry.getValue()。isopen()){entry.getValue()。 }}}}} / ** *すべてのオンラインユーザーのリアルタイムエンジニアリング検査ページにメッセージを送信 * * @Paramメッセージ * @Throws IOException * / public void sendmessagetojsp(final textmessageTojsp(final textmessageTojsp(final textmessageTojsp)throws {iterator <entr <entry <entry、websocketessession >> it = usersocketsessemap)。 // multiThreaded Mass sending while(it.hasnext()){final entry <string、websocketsession> entry = it.next(); if(entry.getValue()。isopen()&& entry.getKey()。contains(type)){new runnable(){public void run(){try {if(entry.getValue()。isopen(){entry.getValue()。 })。始める(); }}}}}}
2。WebSocketの握手処理のためのフロントデスクを作成します
<script> var path = '<%= basepath%>'; var userid = 'lys'; if(userid == -1){window.location.href = "<%= basepath2%>" rel = "external nofollow"; } var jspcode = userid+"_ aaa"; var WebSocket; if(windocket 'in window){websocket = new websocket( "ws://" + path + "wsmy?jspcode =" + jspcode); } else if( 'mozwebsocket' in window){websocket = new MozWebsocket( "ws://" + path + "wsmy?jspcode =" + jspcode); } else {websocket = new Sockjs( "http://" + path + "wsmy/sockjs?jspcode =" + jspcode); } websocket.onopen = function(event){console.log( "websocket:connected"); console.log(event); }; websocket.onmessage = function(event){var data = json.parse(event.data); console.log( "websocket:メッセージ-norm"、data); Alert( "WebSocket:メッセージを受信した"); }; websocket.onerror = function(event){console.log( "websocket:エラーが発生した"); console.log(event); }; websocket.onclose = function(event){console.log( "websocket:close"); console.log(event); } </script>3。コントローラーコールを介したWebSocketバックグラウンドプッシュ
/** *プロジェクト名:価格 *ファイル名:garlicpricecontroller.java *パッケージ名:com.yun.price.garlic.controller *日付:2016年6月23日午後3時23:46 *著作権(c)2016,[email protected]@QQ.com */パッケージcom.yun.price.garlic.controller; java.io.ioexceptionをインポートします。 Import Java.util.date; java.util.listをインポートします。 javax.annotation.resourceをインポートします。 javax.servlet.http.httpservletrequestをインポートします。 javax.servlet.http.httpsessionをインポートします。 Import org.springframework.beans.factory.annotation.autowired; org.springframework.stereotype.controllerをインポートします。 org.springframework.web.bind.annotation.requestmappingをインポートします。 org.springframework.web.bind.annotation.RequestMethodをインポートします。 Import org.springframework.web.bind.annotation.responsebody; Import org.springframework.web.context.request.RequestContExtholder; Import org.springframework.web.context.request.servletrequestattributes; Import org.springframework.web.servlet.modelandview; import org.springframework.web.socket.textmessage; com.google.gson.gsonbuilderをインポートします。 com.yun.common.entity.datagridをインポートします。 com.yun.price.garlic.dao.entity.garlicpriceをインポートします。 com.yun.price.garlic.model.garlicpricemodelをインポートします。 com.yun.price.garlic.service.garlicpriceserviceをインポートします。 com.yun.websocket.mywebsockethandlerをインポートします。 /** *タイトル:garlicpricecontroller <br/> *説明: * * @company:qingdao litu hi-tech <br/> * @author:liu yunsheng * @version:v1.0 * @since:jdk 1.7.0_80 * @date:6月23日garlicpricecontroller {@resource mywebsockethandler mywebsockethandler; @RequestMapping(value = "garlicpricecontroller/testwebsocket"、method = {requestmethod.post、requestmethod.get}、生成= "application/json; charset = utf-8")@responsebody public string testwebsocket()throws ioexception {mywebscoktethandler.endmessagegeto(new bendmessageto(new bedsandler.sendmessageTo) gsonbuilder()。create()。tojson( "/" number/":/"+"garlicpricecontroller/testwebsocket"+"/" ")、" aaa "); return" 1 ";}}}
4。使用したJARパッケージ
<Dependency> groupId> org.springframework </groupid> <artifactid> spring-websocket </artifactid> <バージョン> 4.0.1.Release </version> </dependency>
5。操作環境
少なくともtomcat8.0以上、そうでなければエラーが報告される場合があります
上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。