spring自帶websocket用於前後臺實時交付
阿新 • • 發佈:2018-11-08
後臺程式碼
package com.ny.until; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; import org.springframework.web.socket.handler.TextWebSocketHandler; @Configuration @EnableWebSocket public class WebSocket implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(chatMessageHandler(),"/webSocketServer"); } @Bean public TextWebSocketHandler chatMessageHandler(){ return new ChatMessageHandler(); } }
package com.ny.until; import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; public class ChatMessageHandler extends TextWebSocketHandler { private static final Map<String,WebSocketSession> users;// 這個會出現效能問題,最好用Map來儲存,key用userid private static Logger LOG = LoggerFactory.getLogger(ChatMessageHandler.class); static { users = new HashMap<String, WebSocketSession>(); } /** * 連線成功時候,會觸發UI上onopen方法 */ @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { LOG.info("connect to the myself websocket success......" + session.getUri().toString().split("\\?")[1]); users.put(session.getUri().toString().split("\\?")[1], session); } /** * 在UI在用js呼叫websocket.send()時候,會呼叫該方法 */ @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { } /** * 給某個使用者傳送訊息 * * @param userName * @param message */ public static void sendMessageToUser(String name, String message) { LOG.info(message.toString()); WebSocketSession user = users.get(name); LOG.info(name); if (user == null) { return; } try { if (user.isOpen()) { LOG.info("給頁面傳送資訊"); user.sendMessage(new TextMessage(message)); } } catch (IOException e) { e.printStackTrace(); } } //連線中斷 @Override public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception { LOG.debug("handleTransportError:websocket myself connection closed......"); } @Override public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception { LOG.info("afterConnectionClosed:websocket myself connection closed......"); } @Override public boolean supportsPartialMessages() { return false; } }
前端寫作程式碼:
// 建立websocket var websocket = null; ws = function(address) { if ('WebSocket' in window) { websocket = new WebSocket(wsAppConfig.path + address); } else { Alert('當前瀏覽器 Not support websocket', false); } return websocket; } onMessage = function(websocket) { websocket.onmessage = function (event) { // event.data就是後臺傳過來的資料,然後做處理 } }