web socket做实时推送

本文介绍了如何使用Spring Boot的WebSocket功能构建实时应用,包括配置ServerEndpoint、处理WebSocket连接状态变化和消息传递,同时展示了如何统计在线用户数量并实现全频道广播。
摘要由CSDN通过智能技术生成

内容来源:点击跳转
主要是这个依赖。

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

配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;


@Configuration
public class Configure{

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

}

websocket 类
当然,若不做人数,统计可去掉。


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;


@Component
@ServerEndpoint("/websocket/{sid}")
public class WebSocket {


    static Log log = LogFactory.getLog(WebSocket.class);
    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static volatile int onlineCount = 0;
    //concurrent包的线程安全Set,用来存放每个客户端对应的Socket对象。
    private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<WebSocket>();
    //与某个客户端的连接会话,需要通过它来给客户端发送数据
    private Session session;


    @OnOpen
    public void open(Session session,@PathParam("sid") String sid){
        this.session = session;
        webSockets.add(this);
        addOnlineCount();   //在线人数+1
        log.info("有新窗口开始监听:"+sid+"   当前在线人数为" + getOnlineCount());
        //sendMessage("已成功建立连接!");
    }

    @OnClose
    public void close(Session session){
        webSockets.remove(this);
        subOnlineCount();   //在线人数-1
    }

    @OnMessage
    public void message(String message){
        //收到客户端消息后调用的方法
        for (WebSocket item : webSockets) {
            item.sendMessage(message);
        }
    }

    public void sendMessage(String message){
        try{
            this.session.getBasicRemote().sendText(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void sendInfoToAll(String message){
        for (WebSocket item : webSockets) {
            //这里全部推送,单独发送需要判断sid
            item.sendMessage(message);
        }
    }

    @OnError
    public void error(Session session,Throwable error){
        error.printStackTrace();
    }



    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
    public static synchronized void addOnlineCount() {
        WebSocket.onlineCount++;
    }
    public static synchronized void subOnlineCount() {
        WebSocket.onlineCount--;
    }


}

controller


@Controller
public class AccessController {


    @RequestMapping("/")
    public String index(){
        return "index";
    }


    @Scheduled(fixedRate = 3000)
    @GetMapping("/visual")
    @ResponseBody
    public List<Integer> visual(){
        List<Integer> collect = Arrays.stream("30,5,20,40,23,50".split(",")).map(element -> (int)(Math.random() * 50 + 1)).collect(Collectors.toList());
        //数据推送
        push(collect.toString().replace("[","").replace("]",""));
        return collect;
    }



    private void push(String message) {
        System.out.println(message);
        WebSocket.sendInfoToAll(message);
    }

}

还有一个html,看文章首页链接
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值