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/
相关推荐
想太多会累i2 小时前
Spring Boot 使用Itext绘制并导出PDF
spring boot·pdf
reasonsummer4 小时前
【办公类-100-01】20250515手机导出教学照片,自动上传csdn+最大化、最小化Vs界面
开发语言·python
Doker 多克5 小时前
Python-Django系列—日志
python·日志
苏三福6 小时前
ros2 hunmle bag 数据包转为图片数据 python版
开发语言·python·ros2humble
大神薯条老师7 小时前
Python零基础入门到高手8.4节: 元组与列表的区别
开发语言·爬虫·python·深度学习·机器学习·数据分析
z人间防沉迷k7 小时前
堆(Heap)
开发语言·数据结构·笔记·python·算法
松树戈7 小时前
plus-ui&RuoYi-Vue-Plus 基于pgSql本地运行实践
前端·vue.js·spring boot·ui
小白学大数据7 小时前
Python爬虫如何应对网站的反爬加密策略?
开发语言·爬虫·python
Eric.Lee20217 小时前
Ubuntu shell指定conda的python环境启动脚本
python·ubuntu·conda·shell
芒果量化8 小时前
量化交易 - 网格交易策略实现与原理解析
python·算法·机器学习·金融