首先 pom.xml
<s parent> <proupId> org.springframework.boot </prôdId> <ArtifActid> printemps-boot-starter-Parent </ artifactive> <version> 1.5.8.release </-version> </parent> <petendency> <proupId> org.apache.commons </prouprid> <ptetifactid> Commons-io </ a a rtifactid> </dpendance> <dependency> <proupId> javax.websocket </proncId> <ArtifactId> javax.websocket-api </ artifactId> <DERSE> 1.0 </ version> <cope> fourni </cope> </pedigency> <dependency> <proupId> org.springFramework </prèmes Id> <letifactId> Spring-websocket </ artifactid> </dependency> <dependency> <proupId> org.springframework.boot </proupId> <Artifactid> printemps-boot-starter-web </retifactid> <cussions> <exclusion> <proupId> org.springframework.boot </ / exclusion> <proupId> org.SpringFramework. GroupID> <ArtifactId> Spring-Boot-Starter-Tomcat </ Artifactid> </clusion> </clusions> </Dependency> <Dependance> <GroupId> org.springFramework.boot </prouprid> <prefactid> Spring-Boot-Starter-Undertow </RetifActid> </Dependance>
接收消息后的处理类 GameHandler:
import 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.springframework.web.socket.WebSocketSession;import org.springframework.web.socket.handler.AbstractWebSocketHandler;public class GameHandler extends AbstractWebSocketHandler { /** * 处理字符串类的信息 * * @param session * @param message * @throws Exception */ @Override protected void handleTextMessage(WebSocketSession session, Message TextMessage) lève l'exception {session.sendMessage (new TextMessage (message.asbytes ())); } / ** * 处理二进制类的信息 * * @param session * @param message * @throws exception * / @Override Protected void GrochebinaryMessage (Session WebSocketSession, message binaryMessage) lance l'exception {session.sendMessage (new BinaryMessage (message.getPayload ())); } / ** * ping-pong * * @param session * @param message * @throws exception * / @Override Protected void handlepongMessage (session WebSocketSession, Session PongMessage) lance une exception {} / ** * 传出错误的处理 * * @param session * @param exception * @throws exception * / @Override Vend Handletransporterror (WebSocketSession, exception de forte } / ** * 连接关闭的处理 * * @param Session * @param status * @throws exception * / @Override public void afterConnectionClosed (section WebSocketSession, statut closestatus) lance l'exception {} / ** * 连接建立后的处理 * * @Param Session * @throws exception * / @Override public Void AfterConnectionEstablisy (webSocketession session) lance exception exception {}}握手信息拦截器 WebSockethandShakeInterceptor:
import java.util.map; import javax.servlet.http.cookie; import org.springframework.http.server.serverhttprequest; import org.springframework.http.server.serverhttponse; import; org.springframework.http.server.servletserverhttprequest; import org.springframework.web.socket.websockethandler; import org.springframework.web.socket.server.handshakeInterceptor; @ @Override bobooleank AVANTHADSHAKE (requête ServerHttpRequest, serverHttpResponse ShR1, WebSockethandler wsh, map <string, object> attributs) lève exception {// 此处可以做一些权限认证的事情或者其他 return true; } @Override public void Afterhandshake (ServerHttpRequest SHR, ServerHTTPResponse SHR1, WebSockethandler WSH, exception excptn) {}}使用 WebSocket 的配置类 WebSocketConfig:
import org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter; import org.springframework.web.socket.config.annotation.enablewebsocket; org.springframework.web.socket.config.annotation.websocketConfigurer; import org.springframework.web.socket.config.annotation.websockethandlergistry; @ configuration @ activerwebsocketpublic class websocketconfig extend webmvcconfigurera registrewebsockethandlers (WebSockethandlerRegistry Registry) {// 允许连接的域, 只能以 http 或 https 开头 String [] permets / {"http://127.0.0.1:1213", "http: // localhost: 1213"}; Registry.AddHandler (GameHandler (), "/ Game"). AddInterceptors (HandshakeInterceptor ()). SetallowEdorigins (perdorigins); } @Bean public GameHandler GameHandler () {return new GameHandler (); } @Bean public WebsockethandShakeInterceptor HandshakeInterceptor () {return new WebSockethandShakeInterceptor (); }}启动类 Lanceur:
@SpringBootApplicationPublic Class Launcher {public static void main (String [] Params) {SpringApplication.Run (Launcher.Class, Params);}}配置文件 Main / Ressources / Application.Properties:
server.port = 1213Server.Session-timeout = 1800Server.undertow.io-threads = 4Server.undertow.worker-threads = 20server.undertow.buffer-size = 1024Server.Direct-Buffers = true = 1024Server.undertow.Direct-Buffers = true =
前端的测试页面 Main / Ressources / statique / index.html
<! Doctype html> <html lang = "zh-cn"> <éad> <meta charset = "utf-8"> <meta http-equiv = "x-ua-compatible" contenu = "ie = edge"> <meta name = "Viewport" contenu = "width = device-width, initial-scale = 1"> <title> gateway gateway </ title> href = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel = "externe nofollow" rel = "Stylesheet"> <! - <link href = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel = "externe nofollow" rel = "Stylesheet"> -> <script src = "https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"> </ script> <script src = "https://cdn.bootcss.min.jquery-scrollto/2.1.2/jquery.scrollto.min.js"> </ script> src = "https://cdnjs.cloudflare.com/ajax/libs/pako/1.0.6/pako.min.js"> </ script> <! - [si lt ie 9]> <script src = "https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"> </ script> <script src = "https://cdn.bootcss.comb/respond.js/1.4.2/reSPond #Message {hauteur: 600px; débordement-y: auto; } </ style> </ head> <body> <div> <h1> page de test WebSocket </h1> <hr /> <div> <div> <label for = "wsaddr"> Websocket: </ label> <v> <span id = "Basic-ws"> ws: //127.0.0.1: 1213 / </pan> <put-type = "Text" Text "id =" Basic-Ws-Aaddr " aria-descriradBy = "Basic-ws" placeholder = "game" data-contrainer = "body" data-place = "top" data-contrac = "链接地址不能为空, 请填写"> </ div> </ div> <button type = "Button" id = "btnconnect" onclick = "connect ();"> <span aria-hidden = "true"> </pank> id = "btnclose" Disabled = "Disabled" onClick = "closewwebsocket ();"> <span aria-hidden = "true"> </span> 断开 </futton> <Button type = "Button" id = "btnSend" Disabled = "Disabled" style = "margin-left: 50px;" onClick = "Send ();"> <span aria-hidden = "true"> </span> 发送消息 </ button> </div> <br/> <textarea id = "inmsg" rows = "5" placeholder = "在这里输入需要发送的信息 ..."> </ textarea> <hr /> <div id = "message"> </v> </v> <script 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: string '})); retour btoa (binarystring); } fonction 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)); Retour Strdata; } var Websocket = null; var wsbaseurl = null; var wsurl = null; fonction init () {wsbaseurl = "ws: //" + window.location.host + "/"; $ ("# basic-ws"). text (wsbaseur); $ (function () {$ ('[data-toggle = "popover"]'). popover ();}); retourne false; } // 关闭 WebSocket 连接 Fonction ClosewWebSocket () {if (WebSocket) {WebSocket.close (); } return false; } // 将消息显示在网页上 fonction setMessageInnerHtml (who, msg) {var message = null; 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%'); retourne false; } // 发送消息 function Send () {if (WebSocket) {var message = $ ("# inmsg"). Val (); WebSocket.Send (zip (message)); setMessageInnerHtml (1, message); } return false; } fonction connect () {var url = $ ("# basic-ws-addr"). val (); if (url.length <= 0) {$ ('# basic-ws-addr'). popover ('show'); setTimeout (function () {$ ('# Basic-Ws-Addr'). Popover ('Hide');}, 3000); } else {wsurl = wsbaseurl + url; if ('Websocket' dans la fenêtre) {WebSocket = new WebSocket (wsurl); // 连接发生错误的回调方法 WebSocket.onerror = function () {setMessageInnerHtml (0, "WebSocket 连接发生错误 ->" + wsurl); $ ("# btnconnect"). RemoveAttr ("Disabled"); $ ("# btnclose"). attr ("handicapé", "désactivé"); $ ("# btnsend"). attr ("handicapé", "désactivé"); }; // 连接成功建立的回调方法 WebSocket.onOpen = function () {setMessageInnerHtml (0, "WebSocket 连接成功 ->" + wsurl); $ ("# btnconnect"). attr ("handicapé", "désactivé"); $ ("# btnclose"). RemoveAttr ("Disabled"); $ ("# btnsend"). reposattr ("handicap"); }; // 接收到消息的回调方法 WebSocket.onMessage = function (event) {setMessageInnerHtml (0, unzip (event.data)); }; // 连接关闭的回调方法 WebSocket.OnClose = function () {setMessageInnerHtml (0, "WebSocket 连接关闭 ->" + wsurl); $ ("# btnconnect"). RemoveAttr ("Disabled"); $ ("# btnclose"). attr ("handicapé", "désactivé"); $ ("# btnsend"). attr ("handicapé", "désactivé"); }; // 监听窗口关闭事件 , 当窗口关闭时 , 主动去关闭 WebSocket 连接 , 防止连接还没断开就关闭窗口 , Server 端会抛异常。 window.onbeforeunLoad = function () {closewwebsocket (); }; } else {alert ('pas supporter WebSocket'); }} return false; } window.onload = init (); </cript> </ body> </html>到此就可以使用 WebSocket 进行前后端的通信了 , 如果大家还有不明白的或者有更好的方法 , 可以在下方的留言区讨论。