springboot + WebSocket实时显示消息

目录

springboot + WebSocket实时显示消息

添加依赖

开启WebSocket支持

建立WebSocketServer

实现Controller

实现前端显示

用于测试:显示到页面的控制台console

用于实践:显示到前端页面


springboot + WebSocket实时显示消息

最近有个web项目要实现在前端实时显示采集到的最新的一张图片,查阅资料后发现WebSocket在实时显示方面比较容易,主要是建立了一个全双工的通信,使前端和后端能够随时通信。比之前所用的轮询要更好一些。

本博客是在我做项目之前使用WebSocket做的一个小测试,证明是可以实现实时显示的。根据网上博客实现了一个实时在线人数的显示,网上给的都不太详细,并且只是将其显示到console中,没有显示到前端。

添加依赖

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

开启WebSocket支持

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

建立WebSocketServer

@ServerEndpoint("/websocket/{sid}")
@Component
public class WebSocketServer {
    static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    //静态变量,用来记录当前在线连接数。
    private static int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;
    //接收sid
    private String sid="";
    /**
     * 连接建立成功调用的方法*/
    @OnOpen
    public void onOpen(Session session,@PathParam("sid") String sid) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
        this.sid=sid;
        try {
            sendMessage("连接成功");
            sendInfo("当前连接用户数为" + getOnlineCount(), null);
        } catch (IOException e) {
            log.error("websocket IO异常");
        }
    }
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
    }
    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息*/
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口"+sid+"的信息:"+message);
        // 群发消息
        for (WebSocketServer item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     *
     * @param session
     * @param error
     */
    @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(String message,@PathParam("sid") String sid) throws IOException {
        System.out.println("------WebSocketServer----------sendInfo-----");
        log.info("推送消息到窗口"+sid+",推送内容:"+message);
        for (WebSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个sid的,为null则全部推送
                if(sid==null) {
                    item.sendMessage(message);
                }else if(item.sid.equals(sid)){
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }
}

实现Controller

@Controller
@RequestMapping("/usercounter")
public class UserCounterController {
    //页面请求
    @GetMapping("/socket/{cid}")
    public ModelAndView socket(@PathVariable("cid") String cid) {
        ModelAndView mav=new ModelAndView("/socket");
        mav.addObject("cid", cid);
        return mav;
    }
}

实现前端显示

<h2 id = "counter">当前连接数目为</h2>
<script>
    var socket;
    var id='${cid}';    // 通过'${cid}'来取得前端传来的cid值
    if(typeof(WebSocket) == "undefined") {
        console.log("您的浏览器不支持WebSocket");
    }else{
        console.log("您的浏览器支持WebSocket");
        //实现化WebSocket对象,指定要连接的服务器地址与端口  建立连接
        socket = new WebSocket("ws://localhost:8843/websocket/"+id);    // 建立连接
        //打开事件
        socket.onopen = function() {
            console.log("Socket 已打开");
        };
        //获得消息事件
        socket.onmessage = function(msg) {
            console.log(msg.data);      // 将数据显示到console
            //发现消息进入    开始处理前端触发逻辑
            var x = document.getElementById("message");
            x.value = msg.data;         // 将数据显示到前端
        };
        //关闭事件
        socket.onclose = function() {
            console.log("Socket已关闭");
        };
        //发生了错误事件
        socket.onerror = function() {
            alert("Socket发生了错误");
            //此时可以尝试刷新页面
        }
    }
</script>

用于测试:显示到页面的控制台console

用于实践:显示到前端页面

分别访问 cid=22, 33, 44,网页会对内容进行自动更新,并且在console中打印调试内容。

springboot + WebSocket实时显示消息

执行localhost:8843/usercounter/socket/22 时 控制台和前端均显示 连接用户数为1

 

springboot + WebSocket实时显示消息

执行localhost:8843/usercounter/socket/33时 控制台和前端均显示 连接用户数为2

springboot + WebSocket实时显示消息

执行localhost:8843/usercounter/socket/44时 控制台和前端均显示 连接用户数为3

此时再回过头查看22 与 33 的网页发现 也显示 连接用户数为3 并且控制台中显示了变化的过程

 

springboot + WebSocket实时显示消息

springboot + WebSocket实时显示消息

 

 

至此,最终证明了WebSocket是能够很好的实现实时显示的内容的。