springboot使用webSocket

websocketservice服务类

java 复制代码
package cn.oyohotels.iot.bff.kiosk.server;


import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import cn.oyohotels.iot.bff.kiosk.entity.socket.SocketView;
import cn.oyohotels.iot.bff.kiosk.utils.JsonUtil;
import org.springframework.stereotype.Component;
import lombok.extern.slf4j.Slf4j;

/**
 * WebSocket服务端
 *
 * @author panghui
 * @version 1.0
 * @since 2019/11/6
 */
@ServerEndpoint("/webSocketServer/{hotelId}")
@Component
@Slf4j
public class WebSocketServer {

    //静态变量,用来记录当前在线连接数
    private static AtomicInteger onlineCount = new AtomicInteger(0);
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

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

    /**
     * 接收的酒店ID
     */
    private String hotelId="";

    /**
     * 连接建立成功
     *
     * @param session
     * @param hotelId
     */
    @OnOpen
    public void onOpen(Session session,@PathParam("hotelId") String hotelId) {
        log.info("当前对象:"+this);
        this.session = session;
        // 将当前的Socket对象放入集合
        webSocketSet.add(this);
        // 增加连接人数 +1
        onlineCount.incrementAndGet();
        log.info("有新窗口开始监听:"+hotelId+",当前在线人数为" + onlineCount.get());
        this.hotelId=hotelId;
        try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        // 移除
        webSocketSet.remove(this);
        // 在线人数减少 -1
        onlineCount.decrementAndGet();
        log.info("有一连接关闭!当前在线人数为" + onlineCount.get());
    }

    /**
     * 收到客户端消息后调用方法
     *
     * @param message 客户端发送过来的消息
     * @param session
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自酒店ID:"+hotelId+"的信息:"+message);
        //群发消息
        for (WebSocketServer webSocketServer : webSocketSet) {
            try {
                webSocketServer.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        error.printStackTrace();
    }
    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }


    /**
     * 群发自定义消息
     */
    public static void sendInfo(SocketView socketView, @PathParam("hotelId") String hotelId) throws IOException {
        String message = JsonUtil.objectToJson(socketView);
        log.info("推送消息到对应酒店,酒店ID:"+hotelId+",推送内容:"+message);
        for (WebSocketServer webSocketServer : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的,为null则全部推送
                if(hotelId==null) {
                    webSocketServer.sendMessage(message);
                }else if(webSocketServer.hotelId.equals(hotelId)){
                    webSocketServer.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }
}

调用WebSocketServer 服务发送消息

java 复制代码
WebSocketServer.sendInfo(socketView,bean.getHotelId().toString());

客户端测试建立连接

java 复制代码
直接使用在线工具:http://ws.douqq.com/
相关推荐
问道飞鱼1 分钟前
【工具知识】在 Spring Boot 项目中结合 IntelliJ IDEA 实现不同环境配置文件选择
java·spring boot·intellij-idea·多环境
xoliu16 分钟前
Pytorch核心基础入门
人工智能·pytorch·python
一瞬祈望10 分钟前
ResNet50 图像分类完整实战(Notebook Demo + 训练代码)
人工智能·python·神经网络·数据挖掘
其美杰布-富贵-李12 分钟前
PyTorch Lightning Callback 指南
人工智能·pytorch·python·回调函数·callback
_codemonster23 分钟前
python易混淆知识点(十六)lambda表达式
开发语言·python
老华带你飞35 分钟前
学生宿舍管理|基于java + vue学生宿舍管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
广东数字化转型1 小时前
RocketMQ从入门到深入
spring boot·rocketmq·java-rocketmq
ArabySide1 小时前
【Spring Boot】理解Spring Bean作用域的设计
spring boot·后端·spring
毕设源码-赖学姐1 小时前
【开题答辩全过程】以 高校图书馆座位预约管理系统为例,包含答辩的问题和答案
java·spring boot
superman超哥1 小时前
仓颉Option类型的空安全处理深度解析
c语言·开发语言·c++·python·仓颉