Java Springboot webSocket簡單實現,調接口推送消息到客戶端socket
后台一般作為webSocket服務器,前台作為client。真實場景可能是后台程序在運行時(滿足一定條件時),去給client發數據。
再補充一個SpringBoot的client吧
1、依賴
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.5.2</version>
</dependency>
2、client代碼
package com.aircas.satellitemanagement.socket.client; import org.java_websocket.client.WebSocketClient; import org.java_websocket.handshake.ServerHandshake; import java.net.URI; public class WsClient extends WebSocketClient { public WsClient(URI serverUri) { super(serverUri); } @Override public void onOpen(ServerHandshake arg0) { System.out.println("握手成功"); } @Override public void onClose(int arg0, String arg1, boolean arg2) { System.out.println("連接關閉"); } @Override public void onError(Exception arg0) { System.out.println("發生錯誤"); } @Override public void onMessage(String arg0) { System.out.println("收到消息" + arg0); } }
package com.aircas.satellitemanagement.socket.client; import org.java_websocket.enums.ReadyState; import java.net.URI; public class Client { // 根據實際websocket地址更改 private static String url = "ws://localhost:9101/webSocket/TT"; public static void main(String[] args) { try { WsClient myClient = new WsClient(new URI(url)); myClient.connect(); // 判斷是否連接成功,未成功后面發送消息時會報錯 while (!myClient.getReadyState().equals(ReadyState.OPEN)) { System.out.println("連接中···請稍后"); Thread.sleep(1000); } myClient.send("MyClient"); System.out.println("發送成功"); myClient.send("test1"); myClient.send("test2"); } catch (Exception e) { e.printStackTrace(); } } }
