Java Springboot webSocket简单实现,调接口推送消息到客户端socket
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(); } } }