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/
相关推荐
梨子串桃子_15 小时前
推荐系统学习笔记 | PyTorch学习笔记
pytorch·笔记·python·学习·算法
文言一心16 小时前
LINUX离线升级 Python 至 3.11.9 操作手册
linux·运维·python
诗词在线16 小时前
中国古代诗词名句按主题分类有哪些?(爱国 / 思乡 / 送别)
人工智能·python·分类·数据挖掘
高锰酸钾_16 小时前
机器学习-L1正则化和L2正则化解决过拟合问题
人工智能·python·机器学习
天天睡大觉17 小时前
Python学习11
网络·python·学习
智航GIS17 小时前
11.11 Pandas性能革命:向量化操作与内存优化实战指南
python·pandas
写代码的【黑咖啡】18 小时前
Python中的Selenium:强大的浏览器自动化工具
python·selenium·自动化
抠头专注python环境配置18 小时前
解决Windows安装PythonOCC报错:从“No module named ‘OCC’ ”到一键成功
人工智能·windows·python·3d·cad·pythonocc
华研前沿标杆游学18 小时前
2026年华研就业实践营|走进字节跳动,解锁科技行业职业新航向
python