spring boot 集成 websocket

1.引入jar

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

2 开启websocket

@Configuration
public class DateConverConfig {
  

    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }


}

3,配置类

@ServerEndpoint(value = "/bigscreen/websocket")
@Component
public class WebSocketServer {

    private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    static List<Session> list =new ArrayList<Session>();
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<>();
    private static Map<String, WebSocketServer> map = new ConcurrentHashMap<>();

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

    @OnOpen
    public void onOpen(Session session) {
        list.add(session);
        this.session = session;
        webSocketSet.add(this);     //加入set中
        //addOnlineCount();           //在线数加1
        log.info("有新连接加入!");
       /* try {
            sendMessage("连接成功");
        } catch (IOException e) {
            log.error("websocket IO异常");
        }*/
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("发生错误");
        webSocketSet.remove(this);
        error.printStackTrace();
    }

    @OnClose
    public void onClose() {

        boolean remove = webSocketSet.remove(this);
        log.info(remove + "     执行关闭方法 设置为离线");
    }

    /**
     * 主动发送消息
     *
     * @param message
     * @throws IOException
     */
    public synchronized void sendMessage(String message) throws IOException {
        if (this.session.isOpen()) {
            synchronized (this.session) {
                if (this.session.isOpen()) {
                    this.session.getBasicRemote().sendText(message);
                }
            }
        }
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println(session.getId()+":"+message);
        if(list.size()>1){
            for (int i = 0; i < list.size(); i++) {
                if(!list.get(i).getId().equals(session.getId())){
                    try {
                        list.get(i).getBasicRemote().sendText(message);
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        log.info(message);
        for (WebSocketServer item : webSocketSet) {
            try {
                if (item.session.isOpen()) {
                    synchronized (item.session) {
                        if (item.session.isOpen()) {
                            item.sendMessage(message);
                        }
                    }
                } else {
                    webSocketSet.remove(item);
                }
            } catch (IOException e) {
                e.printStackTrace();
                webSocketSet.remove(item);
                continue;

            }
        }
    }
}

4.调用方法

5.前端


$(function() {
    if("WebSocket" in window){
        //   websocket = new WebSocket("ws://localhost:8088/websocket");
        console.log("websocket 建立连接")
    }else{
        alert("请使用谷歌或360浏览器!");
    }
    websocket.onopen = function () {
        console.log("数据发送中");
    }
    websocket.onerror = function () {
        console.log("websocke连接异常!");
    }
//连接关闭的回调方法
    websocket.onclose = function () {
        console.log("webSocket已关闭");
    }
//监听窗口关闭事件,当窗口关闭时,主动去关闭WebSocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function () {
        websocket.close();
    }
    // 20秒后开始接数据,防止查库操作没完成先执行了此方法
        websocket.onmessage = function (e) {
            webSocketData = JSON.parse(e.data);
            if (webSocketData.equipmentCode){
                // 没数据
                oneData == null;
                siteCurrentData = getCurrentData2(webSocketData);
            } else {
                // 有数据,刷新右侧曲线图
                if (webSocketData.siteId==siteidTree){
                    options.xAxis.data.push(formatTimestamp(webSocketData.dataTime));
                    options.series[0].data.push(webSocketData.ois);
                    options.series[1].data.push(webSocketData.pmx);
                    options.series[2].data.push(webSocketData.voc);
                    var myChart = echarts.init(document.getElementById("polImg"));
                    myChart.setOption(options);
                }
                newDataOne = null;
                oneData == null;
                siteCurrentData = getCurrentData(webSocketData);

            }

        }



 
})

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值