Java 实现WebSocket主动推送消息
Java 实现WebSocket主动推送消息
1、在pom.xml中添加jar包依赖
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>5.0.7.RELEASE</version> </dependency>
2、Java后端代码(服务端 )
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import java.util.concurrent.CopyOnWriteArraySet; /** * @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端, * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端 */ @ServerEndpoint("/dnh/websocket") @Component public class WebsocketService { private static final Logger logger = LoggerFactory.getLogger(WebsocketService.class); private Session session; private static final CopyOnWriteArraySet<WebsocketService> SESSIONS = new CopyOnWriteArraySet<>(); @OnOpen public void onOpen(Session session) { this.session=session; SESSIONS.add(this); logger.info("websocket连接成功,总数为:"+SESSIONS.size()); } @OnClose public void onClose() { SESSIONS.remove(this); logger.info("websocket断开连接,总数为"+SESSIONS.size()); } @OnMessage public void onMessage(String message) { logger.info("收到的消息:"+message); } /** * 发送消息(将数据转为String/JSON) * @param message 内容 */ public void sendMessage(String message){ try { for (WebsocketService websocketService:SESSIONS){ logger.info("【websocket消息】广播消息:{}"+message); try { websocketService.session.getBasicRemote().sendText(message); }catch (Exception e){ logger.error(e.getMessage(), e); } } }catch (Exception e){ logger.error(e.getMessage(), e); } } }
提供一个详细可参考:https://www.cnblogs.com/xdp-gacl/p/5193279.html