SpringBoot中使用Websocket進行訊息推送
阿新 • • 發佈:2019-01-04
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@Log4j @Component @ServerEndpoint("/websocket/{id}") public class WebsocketServer { private static Map<String, Session> connections = new HashMap<>(); private Session session; @OnOpen public void onOpen(Session session, @PathParam("id") String id) { this.session = session; connections.put(id, session); } @OnMessage public void onMessage(String text){ log.info("WebSocket連線數:" + connections.size()); String[] s = text.split("]#!]"); Session ses = connections.get(s[0]); try { ses.getBasicRemote().sendText(s[1]); } catch (IOException e) { MythException.recode("websocket伺服器異常:"+e.getMessage(), e, WebsocketServer.class); } } @OnError public void onError(Throwable throwable) { throwable.printStackTrace(); log.error(throwable.getMessage()); } @OnClose public void onClosing() throws IOException { connections.remove(session); session.close(); } }
@Component @Log4j @ClientEndpoint public class WebSocketClient { private Session session; @OnOpen public void onOpen(Session session) { this.session = session; } @OnMessage public void onMessage(String text) throws IOException { session.getBasicRemote().sendText(text); } @OnError public void onError(Throwable throwable) { log.error(throwable.getMessage()); } @OnClose public void onClosing() throws IOException { // log.info("連線關閉"); session.close(); } public void sendMessage(String toId, String text) throws IOException { text = toId + "]#!]" + text; // log.info(text); onMessage(text); } public static WebSocketClient connect(String url) throws Exception { WebSocketContainer wsc = ContainerProvider.getWebSocketContainer(); WebSocketClient client = new WebSocketClient(); wsc.connectToServer(client, new URI(url)); return client; } }
WebSocketClient client; try { client = WebSocketClient.connect("ws://wx.jjyouhuigo.com/websocket/system"); // 傳送訊息, id 為接受者id, text為傳送的資訊 client.sendMessage(id, System.currentTimeMillis()+" 檔案匯入有錯誤,請重新配置後匯入"); // 關閉連線 client.onClosing(); } catch (Exception e) { e.printStackTrace(); }
var ws = new WebSocket("ws://127.0.0.1/websocket/" + id);
ws.onopen = function () {
console.log("open");
};
ws.onmessage = function (evt) {
console.log(evt.data)
};
ws.onclose = function (evt) {
console.log("close");
};
ws.onerror = function (evt) {
console.log("error");
};