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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • java查看环境变量的命令_java环境变量配置好了

    java查看环境变量的命令_java环境变量配置好了Linux是一个多用户的操作系统。每个用户登录系统后,都会有一个专用的运行环境。通常每个用户默认的环境都是相同的,这个默认环境实际上就是一组环境变量的定义。在Windows下,查看环境变量的命令是:set,这个命令会输出系统当前的环境变量。Linux下Linux查看环境变量准确的说是REDHAT下应该如何查看呢,命令是:export如果你想查看某一个名称的环境变量,命令是:echo$环境变量名,…

    2022年10月1日
    1
  • 开机后弹出女神联盟广告_diagnosticservicehost无法启动

    开机后弹出女神联盟广告_diagnosticservicehost无法启动解决WINXP系统开机后弹出Generichostprocessforwin32services遇到问题需要关闭!出现上面这个错误一般有三种情况。1.就是病毒。开机后会提示GenericHostProcessforWin32Services遇到问题需要关闭”“RemoteRrocedureCall(RPC)服务意外终止,然后就自动重起电脑。一般该病毒会…

    2022年10月12日
    3
  • java与数据库连接的步骤_java与数据库的连接怎么实现

    java与数据库连接的步骤_java与数据库的连接怎么实现1.加载驱动Class.forname(数据库驱动名);2.建立数据库连接使用DriverManager类的getConnection()静态方法来获取数据库连接对象,其语法格式如下所示:Connectionconn=DriverManager.getConnection(Stringurl,Stringuser,Stringpass);其中url–数据库连接字符串….

    2025年12月8日
    4
  • python中md5加密的实现

    python中md5加密的实现python中md5加密的实现MD5消息摘要算法:(英语:MD5Message-DigestAlgorithm),一种被广泛使用的密码散列函数,可以产生出一个128位(16字节)的散列值(hashvalue),用于确保信息传输完整一致。MD5是最常见的摘要算法,速度很快,生成结果是固定的128bit字节,通常用一个32位的16进制字符串表示。Python的hashlib提供了常见的摘要算法,如MD5,SHA1等等。摘要算法又称哈希算法、散列算法。它通过一个函数,把任意长度的数据转换为一个

    2022年7月11日
    14
  • 判断三点是顺时针还是逆时针方向

    判断三点是顺时针还是逆时针方向

    2021年9月10日
    127
  • wsl2 固定ip_wsl2 ssh

    wsl2 固定ip_wsl2 ssh给win10下的wsl2设置固定ip地址

    2022年8月31日
    5

发表回复

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

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