首先 pom.xml
<Parent> <MoupRoD> org.springframework.boot </proupid> <artifactid> spring-boot-starter-parent </artifactid> <versers> 1.5.8.release </verversion> </rent> <pendency> <proupid> org.apache.commons </groupid> <artifactid> commons-io </a rtifactid> </pendency> <pendency> <uproupid> javax.websocket </proupid> <artifactid> javax.websocket-api </arfactid> <versers> 1.0 </verversion> <cope> proporcionó </pope> </dependence> <epardency> <grupid> org.springframework </proup ID> <SartifactID> Spring-Websocket </artifactid> </pendency> <epardency> <MoupRid> org.springframework.boot </proupid> <artifactid> spring-boot-starter-web </artifactid> <excusions> <extusion> <uproupid> org.springframe.boot </////////////exclusions GroupId> <ArifactID> Spring-Boot-Starter-Tomcat </arfactid> </extusion> </excusions> </dependence> <pendency> <MoupRupid> org.springframework.boot </groupId> <artifactID> spring-boot-starter-untowwwew </artifactid> </pendency>
接收消息后的处理类 GameHandler:
import java.net.uri; import org.springframework.web.socket.binaryMessage; import org.springframework.web.socket.closestatus; import og.springframework.web.socket.pongmessage; import og.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, TextMessage mensaje) lanza la excepción {session.sendMessage (new TextMessage (Message.asBytes ())); } / ** * 处理二进制类的信息 * * @param session * @param Mensaje * @throws Exception * / @Override void HaneBinaryMessage (Session WebSocketSession, Mensaje BinaryMessage) lanza la excepción {session.sendMessage (New BinaryMessage (Message.getPayLoad ())); } / ** * ping-pong * * @param session * @param Mensaje * @throws Exception * / @Override Void HandlePongMessage (Session de WebSocketSession, Mensaje PongMessage) Lanza excepción {} / ** * 传出错误的处理 * * @param Session * @Param Exception * @throws Exception * / @Override Void HandletrorRorror (Sessionsessession de Toilles). } / ** * 连接关闭的处理 * * @param session * @param status * @throws Exception * / @Override public void AfterConnectionClosed (WebSocketSession Session, CloseStatus Status) lanza la excepción {} / ** * 连接建立后的处理 * * @param Session * @throws Exception * / @Override public握手信息拦截器 WebSocketHandshakeInterceptor:
import java.util.map; import javax.servlet.http.cookie; import org.springframework.http.server.serverhttprequest; import org.springframework.http.server.serverhttpesponse; import org.springframework.http.server.servletserverhtttprequest; import org.springframework.web.socket.websockethandler; importar org.springframework.web.socket.server.handshakeinterceptor; public ANTESHANDSHAKE (Solicitud de serverhttpRequest, serverhttpResponse shR1, WebSocketHandler WSH, map <string, object> atributes) lanza la excepción {// 此处可以做一些权限认证的事情或者其他 return true; } @Override public void AfterHandshake (ServerHttprequest SHR, ServerHttPesponse Shr1, WebSocketHandler WSH, Exception Excptn) {}}使用 WebSocket 的配置类 WebSocketCig:
importar org.springframework.context.annotation.bean; import org.springframework.context.annotation.configuration; import org.springframework.web.servlet.config.annotation.webmvcconfigerereradapter; import org.springframework.web.socket.config.configatation.eNAntapter; org. RegisterWebSocketHandlers (Registro de WebSocketHandlerRegistry) {// 允许连接的域, 只能以 http 或 https 开头 string [] lowoRigins = {"http://127.0.0.1:1213", "http: // localhost: 1213"}; Registry.AddHandler (GameHandler (), "/Game"). AddInterceptors (HandShakeInterceptor ()). SetAlowEdorigins (IllowOrigins); } @Bean Public GameHandler GameHandler () {return New GameHandler (); } @Bean Public WebSocketHandShakeInterceptor HandShakeInterceptor () {return New WebSocketHandShakeInterceptor (); }}启动类 Lanzador:
@SpringBootApplicationPublic Class Launcher {public static void main (string [] params) {springApplication.run (launcher.class, params);}}配置文件 Main/Recursos/Application.Properties:
servidor.port = 1213Server.Session Tiempout = 1800Server.undertow.io-Threads = 4Server.undertow.Worker-Threads = 20Server.undertow.Buffer-Size = 1024Server.undertow.Buffers-Per-Region = 1024Server.undertow.Direct-Buffers = verdadero verdadero
前端的测试页面 main/recursos/static/index.html
< href = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel = "externo nofollow" rel = "Stylesheet"> <!-<Link href = "https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel = "externo nofollow" rel = "Stylesheet">-> <script src = "https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"> </script> <script src = "https://cdn.bootcss.com/jquery-scrollto/2.1.2/jquery.scrollto.min.js"> </script> <script> src = "https://cdnjs.cloudflare.com/ajax/libs/pako/1.0.6/pako.min.js"> </script> <!-[if LT IE 9]> <script src = "https://cdn.bootcss.com/html5shiv/3.7.3/html5shiv.min.js"> </script> <script src = "https://cdn.bootcss.com/dpond.js/1.4.2/rponder.min.js"> </script> <? #message {altura: 600px; Overflow-y: Auto; } </style> </head> <body> <div> <h1> Página de prueba de WebSocket </h1> <hr/> <div> <div> <label for = "wsaddr"> dirección de websocket: </selete> <div> <span id = "básico-ws"> ws: //127.0.0.1: 1213/ </ </ </ </span type = "text" id = "id =" " Aria-DesscribedBy = "Basic-WS" PlaceHolder = "Game" Data-Conseiner = "Body" data-placation = "top" data-Content = "链接地址不能为空, 请填写"> </div> </div> <button type = "button" id = "btnconnect" onclick = "conection ();"> <span hidenDden = "verdadero"> </span> 连接 <<boton button "Button" Button " id = "btnclose" discapaced = "Disabled" onClick = "CloseWebSocket ();"> <span aria-hidden = "true"> </span> 断开 </boton> <button type = "button" id = "btnsend" desactivado = "desactivado" style = "margin-left: 50px;"; " onClick = "send ();"> <span aria-hidden = "true"> </span> 发送消息 </boton> </div> <br/> <textARea id = "inmsg" Rows = "5" PlaceHolder = "在这里输入需要发送的信息 ..."> </extArea> <hr/> <Div Id = "Mensaje"> </div> </iv> <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, {a: 'string'}); regreso 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.Aply (NULL, nuevo UINT16Array (datos)); return strData; } var webSocket = null; var wsbaseurl = null; var wsurl = nulo; función init () {wsbaseurl = "ws: //" + window.location.host + "/"; $ ("##básico-ws"). texto (wsbaseurl); $ (function () {$ ('[data-toggle = "popover"]'). popover ();}); devolver falso; } // 关闭 WebSocket 连接 Función CloseWebSocket () {if (WebSocket) {WebSocket.close (); } return false; } // 将消息显示在网页上 función setMessageInnerHtml (Who, msg) {var Message = null; if (quién === 1) {message = '<div role = "alerta"> 本地:' + msg + '</div>'; } else {message = '<div role = "alerta"> 服务器:' + msg + '</div>'; } document.getElementById ('Mensaje'). InnerHtml = (document.getElementById ('Mensaje'). InnerHtml + Mensaje); $ ("#Mensaje"). ScrollTO ('100%'); devolver falso; } // 发送消息 función send () {if (WebSocket) {var Message = $ ("#Inmsg"). Val (); websocket.send (zip (mensaje)); setMessageInnerHtml (1, mensaje); } return false; } function Connect () {var url = $ ("#básico-ws-addr"). val (); if (url.length <= 0) {$ ('#básico-ws-addr'). popover ('show'); setTimeOut (function () {$ ('#básico-ws-addr'). popover ('hide');}, 3000); } else {wsurl = wsbaseurl + url; if ('WebSocket' en Window) {WebSocket = New WebSocket (WSURL); // 连接发生错误的回调方法 WebSocket.Onerror = function () {setMessageInnerHtml (0, "WebSocket 连接发生错误 ->" + wsurl); $ ("#btnconnect"). removeattr ("discapacitado"); $ ("#btnclose"). attr ("discapacitado", "discapacitado"); $ ("#btnsend"). attr ("discapacitado", "discapacitado"); }; // 连接成功建立的回调方法 webSocket.Onopen = function () {setMessageInnerHtml (0, "WebSocket 连接成功 ->" + wsurl); $ ("#btnconnect"). attr ("discapacitado", "discapacitado"); $ ("#btnclose"). removeattr ("discapacitado"); $ ("#btnsend"). removeattr ("discapacitado"); }; // 接收到消息的回调方法 webSocket.onmessage = function (event) {setMessageInnerHtml (0, unzip (event.data)); }; // 连接关闭的回调方法 WebSocket.Onclose = function () {setMessageInnerHtml (0, "WebSocket 连接关闭 ->" + WSURL); $ ("#btnconnect"). removeattr ("discapacitado"); $ ("#btnclose"). attr ("discapacitado", "discapacitado"); $ ("#btnsend"). attr ("discapacitado", "discapacitado"); }; // 监听窗口关闭事件 , 当窗口关闭时 , 主动去关闭 主动去关闭 主动去关闭 连接 防止连接还没断开就关闭窗口 防止连接还没断开就关闭窗口 防止连接还没断开就关闭窗口 端会抛异常。 window.onbeforeunload = function () {CloseWebSocket (); }; } else {alert ('no es compatible con WebSocket'); }} return false; } window.onload = init (); </script> </body> </html>到此就可以使用 WebSocket 进行前后端的通信了 , 如果大家还有不明白的或者有更好的方法 可以在下方的留言区讨论。