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/
相关推荐
创新技术阁3 分钟前
FastAPI 的两大核心组件:Starlette 和 Pydantic 详解
后端·python
关山月5 分钟前
被低估的服务器发送事件(SSE)
python
DeepLink23 分钟前
Python小练习系列:学生信息排序(sorted + key函数)
python·求职
项目申报小狂人27 分钟前
CUDA详细安装及环境配置——环境配置指南 – CUDA+cuDNN+PyTorch 安装
人工智能·pytorch·python
学c真好玩37 分钟前
4.1-python操作wrod/pdf 文件
开发语言·python·pdf
东方佑38 分钟前
使用Python解析PPT文件并生成JSON结构详解
python·json·powerpoint
Auroral15640 分钟前
一文搞懂python实现邮件发送的全流程
python
计算机-秋大田42 分钟前
基于Spring Boot的轻型卡车零部件销售平台的设计与实现(LW+源码+讲解)
java·vue.js·spring boot·后端·课程设计
大霸王龙42 分钟前
LLM(语言学习模型)行为控制技术
python·深度学习·学习
我不是大佬zvj44 分钟前
PyGame开发贪吃蛇小游戏
python·pygame