SpringMVC整合WebSocket【使用原生API】
阿新 • • 發佈:2022-04-10
使用JSR 356 API編寫WebSocket應用,借鑑地址:https://www.baeldung.com/java-websockets
1.新增依賴
<dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.1</version> </dependency>
2.編寫一些配置【可忽略】
packagecn.coreqi.servletsocketdemo.config; import javax.servlet.http.HttpSession; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; /** * 獲取session所在的 httpSession */ public class GetHttpSessionConfigurator extendsServerEndpointConfig.Configurator { @Override public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) { HttpSession httpSession = (HttpSession) request.getHttpSession(); sec.getUserProperties().put(HttpSession.class.getName(), httpSession); } }
3.編寫服務端端點
package cn.coreqi.servletsocketdemo.websocket; import cn.coreqi.servletsocketdemo.config.GetHttpSessionConfigurator; import cn.coreqi.servletsocketdemo.model.DefaultResultModel; import com.alibaba.fastjson.JSONObject; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.util.HashMap; import java.util.Map; @Component @ServerEndpoint(value = "/websocket/{projectId}",configurator = GetHttpSessionConfigurator.class) public class WebSocketTest { // 儲存所有的使用者session private static Map<String, Session> SESSION_MAP = new HashMap<>(); @OnOpen public void onOpen(Session session, @PathParam(value="projectId")String projectId) { DefaultResultModel model = new DefaultResultModel(); model.setNow(System.currentTimeMillis()); model.setData(projectId); model.setMsg("onOpen"); session.getAsyncRemote().sendText(JSONObject.toJSONString(model)); } @OnError public void onError(Throwable t) { System.err.println("WebSocket出錯了"); t.printStackTrace(); } @OnClose public void onClose() { } @OnMessage public void onMessage(Session session,String message) { DefaultResultModel model = new DefaultResultModel(); model.setNow(System.currentTimeMillis()); model.setData(message); model.setMsg("onMessage"); session.getAsyncRemote().sendText(JSONObject.toJSONString(model)); } }
4.前端頁面【需要瀏覽器原生支援WebSocket】
<script type="text/javascript"> var div = document.getElementById('div'); var prefix = "ws://localhost:8080/"; var websocketUrl = prefix + 'websocket/7777'; var socket = new WebSocket(websocketUrl); socket.onopen = function(event){ console.log(event); socket.send('websocket client connect test'); } socket.onclose = function(event){ console.log(event); } socket.onerror = function(event){ console.log(event); } socket.onmessage = function(event){ console.log(event) div.innerHTML += ('接受到伺服器訊息:' + event.data); } </script>