原创

springboot 集成 websocket

引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

新建websocket服务

@Component
@ServerEndpoint("/websocket/{clientId}")
public class WebSocket {

    // 存放每个客户端对应的 webSocket对象
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>();

    // 与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;

    // 客户端id,通过它来确定给那个客户端发送消息
    private String clientId;

    /**
     * 连接建立成功调用的方法
     * @param clientId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("clientId") String clientId){
        System.out.println("连接建立:" + clientId);
        this.session = session;
        this.clientId = clientId;
        webSocketSet.add(this);
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        System.out.println("连接关闭:" + this.clientId);
        webSocketSet.remove(this);
    }

    /**
     * 实现服务器主动推送
     * @param messageObj
     */
    public void sendMessage(Object messageObj){
        String text = JSON.toJSONString(messageObj);
        this.session.getAsyncRemote().sendText(text);
    }

    /**
     * 服务器向客户端发送消息
     * @param clientId
     * @param messageObj
     */
    public void sendInfo(String clientId,Object messageObj){
        for (WebSocket webSocket : webSocketSet){
            if (webSocket.clientId.equals(clientId)){
                webSocket.sendMessage(messageObj);
            }
        }
    }

}

在需要的类中,引入websocket服务,发送消息

public class Test {

    @Autowired
    private WebSocket websocket;

    public void test(){
        websocket.sendInfo("测试客户端id","测试消息");
    }

}
正文到此结束