给Web端Websocket推送

本文详细介绍如何在Spring Boot项目中使用WebSocket实现服务器与客户端的实时双向通信。从引入依赖到创建WebSocketServerEndpoint,再到发送和接收消息,一步步解析WebSocket的集成与使用。同时,提供了完整的代码示例,帮助读者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在pom中引入jar包


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-web</artifactId>
                </exclusion>
            </exclusions>
        </dependency>        

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

 

2、首先需要引入类WebSocketServerEndpoint,代码如下:


package com.zxycloud.service;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
 
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@ServerEndpoint(value = "/searchTa/websocket")
@Component
public class WebSocketServerEndpoint {
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServerEndpoint> webSocketSet = new CopyOnWriteArraySet<WebSocketServerEndpoint>();
 
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    
    protected final Logger logger = LoggerFactory.getLogger(this.getClass()); 
 
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        logger.info("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
             sendMessage("连接成功");
        } catch (IOException e) {
            logger.error("websocket IO异常");
        }
    }
    //    //连接打开时执行
    //    @OnOpen
    //    public void onOpen(@PathParam("user") String user, Session session) {
    //        currentUser = user;
    //        System.out.println("Connected ... " + session.getId());
    //    }
 
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        logger.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }
 
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        logger.info("来自客户端的消息:" + message);
 
        //群发消息
/*        for (WebSocketServerEndpoint item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
    }
 
    /**
     * 
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("发生错误");
        error.printStackTrace();
    }
 
 
    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
 
 
    /**
     * 群发自定义消息
     * */
    public static void sendInfo(String message) throws IOException {
        //logger.info(message);
        for (WebSocketServerEndpoint item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }
 
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    public static synchronized void addOnlineCount() {
        WebSocketServerEndpoint.onlineCount++;
    }
 
    public static synchronized void subOnlineCount() {
        WebSocketServerEndpoint.onlineCount--;
    }
}

 

3、在想要给前端发送消息的地方调用WebSocketServerEndpoint的sendInfo方法


                JSONObject jsonobject = new JSONObject();
                jsonobject.put("address", address);
                jsonobject.put("createTime", String.valueOf(json.get("msgCreateTime")));
                jsonobject.put("deviceid", deviceid);

                 try {
                     WebSocketServerEndpoint.sendInfo(jsonobject.toString());
                     logger.info("WebSocke连接成功!");
                 }catch (IOException e) {
                     logger.info("WebSocke连接失败!");
                 }

前端监控着/searchTa/websocket这个地址,有消息过来就会显示推送。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值