pom.xml
<parent> groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-parent </artifactid> <バージョン> 1.5.8.Release </version> </parent> <deplency> org.apache.commons </groupid> commons-otio </a rtifactid> </dependency> <dependency> <groupid> javax.websocket </groupid> <artifactid> javax.websocket-api </artifactid> <バージョン> 1.0 </version> <scope> id> <artifactid> spring-websocket </artifactid> </dependency> <dependency> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-starter-web </artifactid> <explusions> <exclusion> <gripurwork.springframework.springframework </boot </ GroupId> <artifactid> spring-boot-starter-tomcat </artifactid> </explusion> </expency> </dependency> <dependency> <groupid> org.springframework.boot </groupid> <artifactid> spring-boot-startertow </artifactid> </depenty>
接收消息后的处理类ゲームハンドラー:
java.net.uri; Import org.springframework.web.socket.binarymessage; Import org.springframework.web.socket.closestatus; import org.springframework.web.socket.pongmessage; Import org.springframework.web.socket.textmessage; import org.sock.textmessage; org.springframework.web.socket.websocketsession; Import org.springframework.web.socket.handler.abstractwebsockethandler; public class gamehandler { / ** * * * * * * * * * * * @param Session * @param sestionsescess * @overrideRideRideRideRideRideRideRideRideCretected Vioid Handletextes message)exception {session.sendmessage(new TextMessage(message.asbytes())); } / ** *处理二进制类的信息 * * @param Session * @paramメッセージ * @throws例外 * / @OverrideプロテクションVoid handleBinaryMessage(websocketsession Session、binarymessage message)スロー例外{session.sendmessage(new binarymessage(mesage.getPayload()); } / ** * ping-pong * * @param Session * @paramメッセージ * @throws例外 * / @Override Protected Void PongMessage(websocketsession Session、PongMessageメッセージ)スロー例外{} / ** * * * @param Session * @param Excement * @param Session * / @overide public boid hangebable sestions } / ** *连接关闭的处理 * * @param Session * @Param Status * @Throws Exception * / @Override public afterconnectionclosed(websocketsession Session、cordestatus status)スロー{} / ** *连接建立后的处理 * * @paramセッション * @throws例外 * / @Override公開void acturnectionStibleStiblished(websocketsessionStileStiblided(握手信息拦截器websockethandshakeinterceptor:
Import java.util.map; Import javax.servlet.http.cookie; Import org.springframework.http.server.serverhttprequest; Import org.springframework.http.serverhttespranss; Import; org.springframework.server.servletserverhttprequest; Import org.springframework.web.socket.websockethandler; import org.springframework.web.socket.server.handshakeInterceptor; PublicShakeInterceptor boultorceptorrimes handshakeinterceptor feryhondshake(serverhttprequest request、serverhttpresponse shr1、websockethandler wsh、map <string、object>属性)スロー例外{//此处可以做一些权限认证的事情或者其他return true; } @Override public void afterhandshake(serverhttprequest shr、serverhttpresponse shr1、websockethandler wsh、例外excptn){}}websocketscocketConfig:
Import.springframework.context.annotation.bean; Import org.springframework.context.annotation.configuration; Import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; Import org.springframework.springframework org.springframework.web.config.annotation.websocketConfigurer; Import org.springframework.web.config.annotation.websockethandlerregistry;@configuration@configuration@configuration@enabablewebsocketpublicクラスWebSocketConfig拡張WebMVCONFIGURERADAPTERCONKURERの拡張RegisterWebsockethandlers(websockethandlerregistry registry){// registry.addhandler(gamehandler()、 "/game")。addinterceptors(handshakeinterceptor())。 } @bean public gamehandler gamehandler(){return new GameHandler(); } @bean public websockethandshakeinterceptor handshakeinterceptor(){return new websockethandshakeInterceptor(); }}启动类ランチャー:
@SpringBootApplicationPublic Class Launcher {public static void main(string [] params){springApplication.run(launcher.class、params);}}}main/resources/application.properties:
Server.port = 1213Server.Session-Timeout = 1800Server.undertow.io-Threads = 4Server.undertow.Worker-Threads = 20Server.undertow.undertow.undertow.undertow.buffers-per-region = 1024server.undertow.undertow.drect-buffers = true
main/resources/static/index.html
<!doctype html> <html lang = "zh-cn"> <head> <meta charset = "utf-8"> <meta http-equiv = "x-ua-compatible" content = "ie = edge"> <meta name = "viewport" content = "width = device-width ="> </pittet href = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel = "external nofollow" rel = "styleSheet"> <! - <link href = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel = "external nofollow" rel = "styleSheet"> - > <スクリプトsrc = "https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"> </script> <scrip src = "https://cdn.bootcss.com/jquery-scrollto/2.1.2/jquery. src = "https://cdnjs.cloudflare.com/ajax/libs/pako/1.0.6/pako.min.js"> </script> <! - [if lt ie 9]> <スクリプトsrc = "https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"> </script> <スクリプトsrc = "https://cdn.bootcss.com/respond.js/1.4.2.2/respond.min.js"> <style> #message {height:600px; Overflow-y:auto; } </style> </head> <body> <div> <h1> websocketテストページ</h1> <hr/> <div> <div> <ラベル= "wsaddr"> websocketアドレス:</label> <div> <span id = "basic-ws"> ws://127.0.0.1:1213/</<入力タイプ= "ID aria-describedby = "Basic-Ws" PlaceHolder = "Game" Data-Container = "Body" Data-Placement = "TOP" DATA-CONTENT = "链接地址不能为空、请填写"> </div> </div> <ボタンタイプ= "ボタン" id = "btnconnect" onclick = "connect(); id = "btnclose" disabled = "disabled" onclick = "closewebsocket();"> <span aria-hidden = "true"> </span>断开</button> <ボタンタイプ= "ボタン" id "btnsend" disabled = "disabled" style = "margin-left:50px;" onclick = "send();"> <span aria-hidden = "true"> </span>发送消息</button> </div> <br/> <textarea id = "inmsg" rows "rows =" 5 "placeholder ="在这里输入需要发送的信息... "> </textarea> <hr/> <div id ="> </div> </div> <> < src = "https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"> </script> <script type = "text/javascript"> function zip(str){var binarystring = pako.gzip(str、{to {to sing '}); return btoa(binarystring); } function unzip(b64data){var strdata = atob(b64data); var chardata = strdata.split( '')。map(function(x){return x.charcodeat(0);}); var bindata = new uint8array(chardata); var data = pako.inflate(bindata); strdata = string.fromcharcode.apply(null、new Uint16Array(data)); strdataを返します。 } var websocket = null; var wsbaseurl = null; var wsurl = null; function init(){wsbaseurl = "ws://" + window.location.host + "/"; $( "#basic-ws")。テキスト(wsbaseurl); $(function(){$( '[data-toggle = "popover"]')。popover();}); falseを返します。 } // } falseを返します。 } // if(who === 1){message = '<div role = "alert">本地:' + msg + '</div>'; } else {message = '<div role = "alert">服务器:' + msg + '</div>'; } document.getElementById( 'message')。innerhtml =(document.getElementById( 'message')。innerhtml + message); $( "#message")。scrollto( '100%'); falseを返します。 } //发送消息関数send(){if(websocket){var message = $( "#inmsg")。val(); websocket.send(zip(message)); setMessageInnerhtml(1、メッセージ); } falseを返します。 } function connect(){var url = $( "#basic-ws-addr")。val(); if(url.length <= 0){$( '#basic-ws-addr')。popover( 'show'); setimeout(function(){$( '#BASIC-WS-ADDR')。ポップオーバー( 'hide');}、3000); } else {wsurl = wsbaseurl + url; if(windocket in window){websocket = new websocket(wsurl); //连接发生错误的回调方法webSocket.onerror = function(){setMessageInnerhtml(0、 "websocket连接发生错误->" + wsurl); $( "#btnconnect")。removeattr( "disabled"); $( "#btnclose")。attr( "disabled"、 "disabled"); $( "#btnsend")。attr( "disabled"、 "disabled"); }; //连接成功建立的回调方法webSocket.Onopen = function(){setMessageInnerhtml(0、 "websocket连接成功->" + wsurl); $( "#btnconnect")。attr( "disabled"、 "disabled"); $( "#btnclose")。removeattr( "disabled"); $( "#btnsend")。removeattr( "disabled"); }; //接收到消息的回调方法webSocket.onmessage = function(event){setMessageInnerhtml(0、unzip(event.data)); }; //连接关闭的回调方法webSocket.onclose = function(){setMessageInnerhtml(0、 "websocket连接关闭->" + wsurl); $( "#btnconnect")。removeattr( "disabled"); $( "#btnclose")。attr( "disabled"、 "disabled"); $( "#btnsend")。attr( "disabled"、 "disabled"); }; //监听窗口关闭事件、当窗口关闭时、主动去关闭websocket连接、防止连接还没断开就关闭窗口、server端会抛异常。window.onbeforeunload = function(){closewebsocket(); }; } else {alert( 'websocketをサポートしていない'); }} falseを返します。 } window.onload = init(); </script> </body> </html>到此就可以使用ウェブソケット进行前后端的通信了、如果大家还有不明白的或者有更好的方法、可以在下方的留言区讨论。