Springフレームワークに基づいて書かれたWebSocketリアルタイムのプッシュ例、特定のコンテンツは次のとおりです
ステップ1:SpringMVCプロジェクトを自分で構築してください。非常にシンプルで、Baidu Onlineで入手できます。次のPOMファイルを追加します。
<! - webSocket-> <dependency> <groupId> org.springframework </groupid> <artifactid> spring-websocket </artifactid> <バージョン> 4.2.4. release </version> </dependency> <dependency> <groupid> org.sprameframework </groupid> springメス<バージョン> 4.2.4.Release </version> </dependency>
私の春のバージョンは4.2.4なので、WebSocketも4.2.4です。スプリングバージョンと同じ保持するのが最善です
ステップ2:メッセージプロセッサを書き込みます
/** *プロジェクト名:springrabbitmq *ファイル名:mymessagehandler.java *パッケージ名:com.zsy.websocket *日付:2018年1月31日11:10:03 am * Copyright(c)2018、Zhaoshouyun all rights reserved。 * */パッケージcom.zsy.websocket; java.io.ioexceptionをインポートします。 java.util.mapをインポートします。 java.util.setをインポートします。 java.util.concurrent.concurrenthashmapをインポートします。 org.apache.commons.lang3.stringutilsをインポートします。 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をインポートします。 /** * className:mymessagehandler * function:webscoketインターフェイスを実装 *日付:2018年1月31日11:10:03 am * @author zhaoshouyun * @since jdk 1.7 */public class mymessagehandlerは、Websockethandler {//ユーザー公開科学的string stringユーザー= / *** USERMAP:ユーザー接続WebCoket情報の保存* @Since JDK 1.7*/プライベート最終的な静的マップ<String、websocketsession> Usermap; static {usermap = new concurrenthashmap <string、websocketsession>(30); } / ***このメソッドは、websocketを閉じるときに呼び出されます* @see org.springframework.web.socket.websockethandler#afterconnectionclosed(org.springframework.socket.websocketsesssion、org.springframework.web.socketsus) cordestatus status)スロー例外{string userid = this.getuserid(session); if(stringutils.isnoneblank(userid)){usermap.remove(userid); system.err.println( "this" + userId + "ユーザーが正常に閉じられました"); } else {system.err.println( "閉じたら、ユーザーIDが空になっている"); }} / ***このメソッドは、websocket Connectionを確立するときに呼び出されます* @see org.springframework.web.socket.websockethandler#afterconnectionectioneStabledished(org.springframework.web.socket.websocketsession) if(stringutils.isnoneblank(userid)){usermap.put(userid、session); session.sendmessage(new TextMessage( "WebSocket Connectionが正常に確立されました!")); }} / ***クライアントがwebsocket.sendを呼び出すと、このメソッドはデータ通信に呼び出されます* @see org.springframework.web.socket.websockethandler handlemessage(websocketessessionセッション、websocketmessage <?> message)スロー例外{string msg = message.toString(); string userid = this.getuserid(session); system.err.println( ""+userId+"ユーザーが送信したメッセージは"+msg);メッセージ= new TextMessage( "サーバーがメッセージを受信しました、msg ="+msg); session.sendmessage(メッセージ); } / ***送信プロセスで例外が発生したら、この方法を呼び出します* @see org.springframework.web.websockethandler#handletransporterror(org.springframework.web.socket.websocketsession、java.lang.throwestable)例外{webSocketMessage <String>メッセージ= new TextMessage( "例外メッセージ:"+e.getMessage()); session.sendmessage(メッセージ); } / ** * * @see org.springframework.web.socket.websockethandler#supportspartialMessages() * / @Override public boolean supportspartialMessages(){return false; } / ** * sendmessageTouser:指定されたユーザーに送信 * @author zhaoshouyun * @param userid * @since jdk 1.7 * / public void sendmessagetouser(string userid、string contents){websocketsession session = usermap.get(userid); if(session!= null && session.isopen()){try {textmessage message = new TextMessage(contents); session.sendmessage(メッセージ); } catch(ioexception e){e.printstacktrace(); }}} / ** * sendmessagetoallusers:すべてのユーザーに送信 * @author zhaoshouyun * @ashouyun * @since jdk 1.7 * / public void sendmessagetoallusers(string contents){set <string> userids = usermap.keyset(); for(string userid:userids){this.sendmessagetouser(userid、contents); }} / ** * getUserid:get user id * @author zhaoshouyun * @param session * @return * @since jdk 1.7 * / private string getuserid(websocketsession session){try {string userid =(string)session.getattributes()。get(user_key); useridを返します。 } catch(Exception e){e.printstacktrace(); } nullを返します。 }}ステップ3:WebSocket関連の構成を記述します。もちろん、XMLで構成できます。私は今XML構成を使用していません、そして私はコード構成を使用しています、そして私はxmlにスキャンパッケージを追加する必要があります<コンテキスト:component-scanベースパッケージ= "com.zsy.websocket" />
/** *プロジェクト名:springrabbitmq *ファイル名:websocketconfig.java *パッケージ名:com.zsy.websocket *日付:2018年1月31日 * 1:10:33 pm * * / / ** *プロジェクト名:springrabbitmq *ファイル名:websocketConfig.java *パッケージ名:com.zsy.websocket *日付:2018年1月31日 * 1:10:33 PM * */パッケージcom.zsy.websocket; org.springframework.context.annotation.beanをインポートします。 org.springframework.context.annotation.configurationをインポートします。 Import org.springframework.web.socket.websockethandler; org.springframework.web.socket.config.annotation.enablewebsocketをインポートします。 org.springframework.web.socket.config.annotation.websocketConfigurerをインポートします。 Import org.springframework.web.socket.config.annotation.websockethandlerregistry; /** * className:webSocketConfig *関数:todo add function。 *日付:2018年1月31日午後1時10分33分 * @author zhaoshouyun * @version * @since JDK 1.7 * / @configuration @enablewebsocket public class websocketconfigはwebsocketconfigurer { / ** *登録ハンドル * @see Web.socket.config.annotation.websocketConfigurer#Registwebsockethandlers(org.scockframework.web.socket.config.annotation.websockethandlerregistry) */ @override public void registwebsthristry(regocketherregistry() "/testhandler").adddinterceptors(new websocketInterceptor()); registry.addhandler(myhandler()、 "/socketjs/testhandler").addInterceptors(new websocketInterceptor())。withsockjs(); } @bean public websockethandler myhandler(){return new mymessagehandler(); }}ステップ4:WebSocketアダプターを書き込みます
パッケージcom.zsy.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; Import org.springframework.web.socket.server.support.httpsessionhandshakeInterceptor; /** * className:webSocketInterceptor *機能:todo add function。 *日付:2018年1月31日午前11時42分34時 * @author zhaoshouyun * @version * @since JDK 1.7 * / public class webSocketInterceptorは、httpsessionhhndshakeInterceptor { / ** * todoを簡単に説明します(オプション)。 * @see org.springframework.web.socket.server.support.httpssessionhandshakeinterceptor#befanyhandshake(org.springframework.http.server.serverhttprequest、org.springframework.http.server.serverhttprepons org.springframework.web.socket.websockethandler、java.util.map) servletserverhttprequest serverhttprequest =(servletserverhttprequest)request; // parameter string userid = serverhttprequest .getservletrequest()。getParameter( "userid"); attributes.put(mymessagehandler.user_key、userid); } trueを返します。 }}ステップ5の対応するJS:
<%@ page Language = "Java" contentType = "text/html; charset = iso-8859-1" pageencoding = "iso-8859-1" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <meta http-equiv = "content-type" content = "text/html; charset = iso-8859-1"> <title> charse //最初に、WebSocketがサポートされているかどうかを判断します(ウィンドウで「WebSocket」){webSocket = new WebSocket( "ws:// localhost:8085/springtest/testhandler?userid = zhaoshouyun"); } else if( 'mozwebsocket' in window){websocket = new mozwebsocket( "ws:// localhost:8085/springtest/testhandler?userid = zhaoshouyun"); } else {websocket = new Sockjs( "http:// localhost:8085/springtest/socketjs/testhandler?userid = zhaoshouyun"); } //接続を開くと、websocket.onopen = function(evnt){console.log( "websocket.onopen"); }; //メッセージを受信すると、websocket.onmessage = function(evnt){alert(evnt.data); }; websocket.onerror = function(evnt){console.log( "websocket.onerror"); }; websocket.onclose = function(evnt){console.log( "websocket.onclose"); }; function seas(){//クライアントはメッセージwebsocket.send(document.getElementbyId( 'msg')。値)を積極的に送信します。 } </script> </head> <body> <入力タイプ= "text" value = "" id = "msg"> <button onclick = "say()"> </button> </body> </html>ステップ6テスト:
パッケージcom.zsy.test.controller; java.util.hashmapをインポートします。 java.util.mapをインポートします。 Import org.springframework.beans.factory.annotation.autowired; Import org.springframework.beans.factory.annotation.value; org.springframework.stereotype.controllerをインポートします。 org.springframework.web.bind.annotation.requestbodyをインポートします。 org.springframework.web.bind.annotation.requestmappingをインポートします。 Import org.springframework.web.bind.annotation.responsebody; com.zsy.websocket.mymessagehandlerをインポートします。 /** * className:testController * function:todo add function。 *日付:2017年12月14日11:11:23 AM * @Author Zhaoshouyun * @version * @since JDK 1.7 */ @Controller Public Class TestController {@AutowiredMyMessageHandlerハンドラー; @RequestMapping( "/get")public string get(){return "index"; } @ResponseBody @RequestMapping( "/get1")public string send(string name){handler.sendmessageTouser( "zhaoshouyun"、 "content fy the server:"+name); 「成功」を返します。 }}上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。