SpringBoo集成webSocket

SpringBoot 集成webSocket

pom依赖

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

添加 WebSocketConfig配置

@Configuration
public class WebSocketConfig {

    /**
     * 开启webSocket支持
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

添加 WebSocketServer配置

@ServerEndpoint("/websocket/{sid}")
@Component
@Slf4j
public class WebSocketServer {

    /**
     * 记录连接数量
     */
    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全set,用来存放每个客户端对应的MyWebSocket对象
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 与摸个客户端的连接回话,需要通过他来给客户端发送数据
     */
    private Session session;

    /**
     * socketId
     */
    private String sid = "";

    /**
     * 连接成功调用
     * @param session
     * @param sid
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        //在线数加1
        addOnlineCount();
        log.info("============》 有新窗口开始监听id为:"+sid+",当前在线人数为:"+getOnlineCount());
        this.sid = sid;
        try {
            sendMessage("连接成功!");
        }catch (IOException e){
            log.error("webSocket io 异常");
        }

    }


    /**
     * 连接关闭调用
     */
    @OnClose
    public void onClose(){
        //从set中删除
        webSocketSet.remove(this);
        //连接数减一
        subOnlineCount();
        log.info("=============》有一个连接关闭,当前在线人数为:"+getOnlineCount());
    }

    @OnMessage
    public void onMessage(String message,Session session){
        log.info("收到来自窗口id为:"+sid+"的信息,内容为:"+message);
        //群发消息
        for(WebSocketServer item : webSocketSet){
            try {
                item.sendMessage(message);
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    /**
     * @param session
     * @param error
     */
    public void onError(Session session, Throwable error){
        log.error("发生错误");
        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     * @param message
     * @param sid
     * @throws IOException
     */
    public static void sendInfo(String message,@PathParam("sid") String sid) throws IOException{
        log.info("推送消息到窗口id为:"+sid+",推送内容为:"+message);
        for(WebSocketServer item : webSocketSet) {
            //这里可以设定值推送给这个sid,为null呢全部推送
            if (sid == null) {
                item.sendMessage(message);
            } else if (item.sid.equals(sid)) {
                item.sendMessage(message);
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

猜你喜欢

转载自blog.csdn.net/u010114906/article/details/83416789