SprinBoot——SpringBoot项目WebSocket推送

SprinBoot——SpringBoot项目WebSocket推送SprinBoot——SpringBoot项目WebSocket推送

大家好,又见面了,我是你们的朋友全栈君。

SpringBoot中创建WebSocket推送

使用SpringBoot创建WebSocket推送比较简单,只需要以下三步即可。

1.创建一个配置类 WebSocketConfig

 package com.adc.da.publish.websocket.config;

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

/**
 * websocket配置类
 *
 * @author: 刘朋
 * <br/>date: 2018-09-20
 */

@Configuration
public class WebSocketConfig {

    /**
     * 定义ServerEndpointExporter
     *
     * @param
     * @return
     * @author 刘朋
     * <br/>date 2018-09-20
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

}

2.创建一个WebSocket推送类

 package com.adc.da.publish.websocket;

import org.springframework.stereotype.Component;

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 java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 单车监控websocket
 *
 * @author 刘朋
 * <br/>date 2018-09-20
 */

@ServerEndpoint("/testWebsocket")
@Component
public class MyWebSocket {

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<>();

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

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        System.out.println("有新连接加入!当前在线人数为" + getOnlineCount());
        try {
            sendMessage("新人上限");
        } catch (IOException e) {
            System.out.println("IO异常");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);

        //群发消息
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发生错误时调用
     */

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

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String message) throws IOException {
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }

}

3.创建前端页面

js中的端口号是本人自己定义的,可以随意定义。

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

<body>
Welcome<br/>
<input id="text" type="text" /><button οnclick="send()">Send</button>    <button οnclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

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

    //判断当前浏览器是否支持WebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://localhost:8107/testWebsocket");
    }
    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>
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/106472.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • MapReduce InputFormat之FileInputFormat

    一:简单认识InputFormat类InputFormat主要用于描述输入数据的格式,提供了以下两个功能:1)、数据切分,按照某个策略将输入数据且分成若干个split,以便确定MapTask的个数即Mapper的个数,在MapReduce框架中,一个split就意味着需要一个MapTask;2)为Mapper提供输入数据,即给定一个spli…

    2022年4月6日
    40
  • c语言malloc函数的用法和意义

    c语言malloc函数的用法和意义当我们需要做一个成绩管理系统,人数可能为全校学生,也可能为一个班的学生,当我们开辟一个班的数组大小时,如果要存储整个学校的人数时,会出现内存不够用的情况;当我们开辟全校人数大小的数组时,输入一个班人数的大小时,会出现内存浪费的情况。为了应对上述问题,我们引入malloc函数。malloc时动态内存分配函数,用于申请一块连续的指定大小的内存块区域以void*类型返回分配的内存区域地址mallo…

    2022年4月29日
    213
  • Torchvision transforms 总结

    Torchvision transforms 总结一.torchvision.transformsTransfoms是很常用的图片变换方式,可以通过compose将各个变换串联起来**1.classtorchvision.transforms.Compose(transforms)**这个类将多个变换方式结合在一起参数:各个变换的实例对象举例:transforms.Compose([ transforms.Center…

    2022年6月24日
    47
  • python导入tensorflow方法_python导入包

    python导入tensorflow方法_python导入包若是你也遇到这个问题,说明你也没有理解tensorflow到底在哪里。当安装了anaconda3.6后,在PyCharm中设置interpreter,这个解释器决定了你在PyCharm环境中写的代码采用什么方式去执行。若是你的设置是anaconda下的python.exe。就会发现在PyCharm中写入importtensorflwoastf时,就会报错,提示没有tensorflow模块,…

    2022年8月27日
    7
  • 十一、代理模式 —专注,做最好的自己!#和设计模式一起旅行#[通俗易懂]

    专注,把更多的时间放到提示自己核心竞争能力上面来!其他的事情交给别人去做吧。故事背景我和设计模式MM开的奶茶店火了,一个是设计模式MM长的好看,波涛汹涌,还有一个是我们的饮品的确好喝,并且还特别在乎用户的体验,上一篇的模板方法模式中,我们最后的例子就询问顾客是否要加入调味料,而不是强制加入。俗话说,人怕出名,猪怕壮!出名后好多的媒体想让我参加他们的节目说一下我这个创业的…

    2022年2月27日
    36
  • Win10下解决Wireshark“没有找到接口”的问题

    Win10下解决Wireshark“没有找到接口”的问题1 wireshark 自带的 Npcap 不支持 win10 需要重新下载 Win10Pcap 下载地址为 http www win10pcap org download 安装时需要关闭 wireshark 然后重新打开 wireshark 即可 2 把 wireshark 自带的 Npcap 程序卸载后 再次打开了 wireshark 程序 成功解决了

    2025年8月2日
    4

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号