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/
相关推荐
databook11 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室11 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三13 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
考虑考虑16 小时前
Jpa使用union all
java·spring boot·后端
用户25191624271116 小时前
Python之语言特点
python
刘立军17 小时前
使用pyHugeGraph查询HugeGraph图数据
python·graphql
数据智能老司机20 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机21 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
c8i1 天前
django中的FBV 和 CBV
python·django
c8i1 天前
python中的闭包和装饰器
python