springboot整合websocket

前言

WebSocket是一种在单个TCP连接上进行全双工通信的协议。WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范。WebSocket API也被W3C定为标准。
WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就直接可以创建持久性的连接,并进行双向数据传输。

springboot项目如何使用websocket

使用websocket非常简单,下面分成四个部分讲解

1.导入依赖

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

2.配置websocket

@Configuration  //配置类交个spring管理
public class WebSocketConfig {
    //websocket需要的bean
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

3.后台使用websocket

后端的websocket主要有一下方法组成
1.onOpen 建立连接(保持连接)时,用于推送消息
2.onClose 连接关闭时
3.onMessage 收到到消息时
4.onError 发生错误时

下面的代码只用于演示进度条的进度值推送
当然我这里用到了自己写的WebSocketDto
用于传输进度值

public class WebSocketDto {

    private static Lock lock = new ReentrantLock();

    public volatile static int process=0;

    public static boolean errorStatus=false;

    public static void addprocess(){
        lock.lock();
        try {
            System.out.println("addprocess得到锁");
            WebSocketDto.process+=1;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//释放锁
        }

    }
    public static void zeroprocess(){
        lock.lock();
        try {
            System.out.println("zero得到锁");
            WebSocketDto.process=0;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

这里正式开始后台websocket代码

@ServerEndpoint("/clientoneWsSocket")  //自定义的服务名
@Service
public class WebSocketController {

        //建立连接推送消息
        @OnOpen
        public void onOpen(Session session){
            while (true) {

                synchronized (session){
                    //    发送消息到页面
//                    this.sendMessage(session,  WebSocketDto.autidinfo);
                    if(WebSocketDto.process<100){
                        if(WebSocketDto.process==1){
                            try {
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        WebSocketDto.addprocess();
                    }

                    this.sendMessage(session,WebSocketDto.process+"");
                    //如果推送发生错误就会断开连接
                    if(WebSocketDto.errorStatus){
//                状态复原
                        WebSocketDto.errorStatus=false;
                        break;
                    }

                    if(WebSocketDto.process==100){
                        //            将状态复原
                        WebSocketDto.zeroprocess();
                    }

                    try {
                        Thread.sleep(100);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }

            }
        }


        @OnClose
        public void onClose() {

        }

        @OnMessage
        public void onMessage(String message,Session session) throws IOException {
            System.out.println(message);
            this.sendMessage(session,"后台收到了你的消息:"+message);
        }

        @OnError
        public void onError(Session session, Throwable error) {
            System.out.println(session+"/");
        }

        //发送消息
        public void sendMessage(Session session, String msg){
            try {
                session.getBasicRemote().sendText(msg);
            } catch (Exception e) {
//                e.printStackTrace();
                System.out.println("信息推送已关闭连接"+e.getMessage());
                //改变状态
                WebSocketDto.errorStatus=true;
            }
        }
}

4.前端使用websocket

使用javascript书写和后端也相差不大,看代码吧

 if ("WebSocket" in window)
            {
                // alert("您的浏览器支持 WebSocket!");
                // 打开一个 web socket
                var ws = new WebSocket("ws://127.0.0.1:8081/clientoneWsSocket");
                ws.onopen = function()
                {
                    // Web Socket 已连接上,使用 send() 方法发送数据
                    ws.send("我是前端页面");
                    // alert("数据发送中...");
                };
                ws.onmessage =async (evt)=>
                {
                    //接收到的数据
                    var received_msg = evt.data;
                    // console.log(received_msg);
                    let af=parseInt(received_msg);
                    //由于我这里使用的时vue 所以可以直接对进度条赋值,如果你使用的时常规的js,那么就需要获取dom进行赋值操作
                    this.processval=af;
                };
                ws.onclose = function()
                {
                    // 关闭 websocket
                    alert("连接已关闭...");
                };
            }else{
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!,无法实时推送新消息");
            }

钉完毕,看下结果吧

在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值