springboot整合websocket发送数据

1.添加pom依赖

 <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
        <version>2.2.12.RELEASE</version>
    </dependency>
      <!-- fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.47</version>
    </dependency>

2.编写websocket的配置文件

 @Component
public class WebSocketConfig {

    @Bean
    /**
     * 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
     */
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }


}

3.编写websocket的相关方法

@Slf4j
//这个注解标注的这个路径就是socket路径,相当于@PostMapping注解的接口路径的作用
@ServerEndpoint(value = "/ivm/alarmSocket")
@Component

public class AlarmSocket {

    @Value("${equNo}")
    private String equNo;

    @Autowired
      private TxtUtil txtUtil;

    /** 记录当前在线连接数 */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /** 存放所有在线的客户端 */
    private static Map<String, Session> clients = new ConcurrentHashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        // 在线数加1
        onlineCount.incrementAndGet();
        clients.put(session.getId(), session);
        log.info("有新连接加入:{},当前在线人数为:{}", session.getId(), onlineCount.get());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(Session session) {
        // 在线数减1
        onlineCount.decrementAndGet();
        clients.remove(session.getId());
        log.info("有一连接关闭:{},当前在线人数为:{}", session.getId(), onlineCount.get());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     *
     * 客户端发送过来的消息
     */
//    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
        this.sendMessage(message, session);
    }

//    @OnMessage
//    public void onMessage(String message) {
//        log.info("服务端收到客户端[{}]的消息:{}",  message);
//        this.sendMessage(message);
//    }


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


    /**
     * 群发消息 服务端向客户端发送消息
     *
     *
     *   服务端向客户端发送消息
     */

    Map<Integer,Date> map=new HashMap<>();

    
    public void sendMessage() throws IOException, ParseException {
        //String txt = txtUtil.readTxt();
        Date nowupdatetime=txtUtil.getmodifyTime();
        Date lastupdatetime=map.get(1);
        if (lastupdatetime==null){
            //转换成时间
            String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            Date datetime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
            lastupdatetime=datetime;
        }
        //log.info("上次更新时间:"+lastupdatetime);
        map.put(1,nowupdatetime);
       // log.info("本次更新时间"+nowupdatetime);
       //本次更新时间大于上次更新时间,则推送消息
        if (nowupdatetime.compareTo(lastupdatetime)==1) {
            String message = "有人闯入,请注意";
            AlarmInfo alarmInfo=new AlarmInfo();
            alarmInfo.setAlarmMsg(message);
            alarmInfo.setAlarmTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nowupdatetime));
            alarmInfo.setEquNo(equNo);
            String json= JSON.toJSONString(alarmInfo);
            log.info("报警信息是:"+json);
            for (Map.Entry<String, Session> sessionEntry : clients.entrySet()) {
                Session toSession = sessionEntry.getValue();
                log.info("服务端给客户端[{}]发送消息:{}", toSession.getId(), json);
                toSession.getAsyncRemote().sendText(json);
               // toSession.getAsyncRemote().
            }
        }
    }
}

4.在使用的地方,注入AlarmSocket,调用 sendMessage 方法

@Service
public class test{

@Resource
private  AlarmSocket alarmSocket;

public void pushMessage(){
alarmSocket.sendMessage() ;

}

}

前端访问的时候,访问路径是 ip+端口/socket的路径,比如 ws://192.168.11.10:8086//ivm/alarmSocket

附上一个简单的前端页面做测试 index.html

<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
<input id="text" type="text" />
<button onclick="send()">Send</button>
<button onclick="closeWebSocket()">Close</button>
<div id="message"></div>
</body>

<script type="text/javascript">
    var websocket = null;

    //判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://192.168.11.10:8086//ivm/alarmSocket");
    } else {
        alert('Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function() {
        setMessageInnerHTML("error");
    };

    //连接成功建立的回调方法
    websocket.onopen = function(event) {
        //setMessageInnerHTML("open");
    }

    //接收到消息的回调方法
    websocket.onmessage = function(event) {
        setMessageInnerHTML(event.data);
    }

    //连接关闭的回调方法
    websocket.onclose = function() {
        setMessageInnerHTML("close");
    }

    //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
    window.onbeforeunload = function() {
        websocket.close();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //关闭连接
    function closeWebSocket() {
        websocket.close();
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值