使用WebScoket实现前后端连接

前端代码

//需要在script标签下面写入这个 不然会报找不到webScoket的错误
let websocket;


//所需参数
data(){
	return {
		//保存webScoket的对象
		websocket: {},
		//连接后端的地址(这里要替换成自己后端的连接地址)
		websocketUrl: 'ws://127.0.0.1:8080/demo/websocket',
		//判断是否重新连接
		lockReconnect: false,
	}
}

//webScoket初始化方法
webScoketInit() {
	var that = this;
	//判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        if (websocket != null) {
            websocket.close();
            websocket = null;
        }
    } else {
        that.$message.error('当前浏览器不支持WebScoket')
    }
    //连接后端的地址
    that.websocket = new WebSocket(that.websocketUrl);

    //连接发生错误的回调方法
    that.websocket.onerror = function (event) {
		//尝试重新连接
        reconnect(that.websocketUrl);  
        console.log(event);
        console.log('连接错误')
    };

    //连接成功建立的回调方法
    that.websocket.onopen = function (event) {
        //心跳检测重置
        heartCheck.reset().start();
        console.log(event);
        console.log('连接开启')
    }


    //接收到消息的回调方法
    that.websocket.onmessage = function (event) {
        //心跳检测重置
        heartCheck.reset().start();
        //获取到后台发送的数据并转为json类型
        let res = JSON.parse(event.data)
    }

    //连接关闭的回调方法
    that.websocket.onclose = function (event) {
		//尝试重新连接
        reconnect(that.websocketUrl);  
        console.log(event);
        console.log('连接关闭')
    }

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

    //重新连接
    function reconnect(url) {
        if (that.lockReconnect) return;
        that.lockReconnect = true;
        //没连接上会一直重连,设置延迟避免请求过多
        setTimeout(function () {
            // that.websocket = new WebSocket(url);
            that.webScoketInit();
            that.lockReconnect = false;
        }, 2000);
    }

    //心跳检测
    var heartCheck = {
        //1分钟发一次心跳,时间设置小一点较好(50-60秒之间)
        timeout: 55000,
        timeoutObj: null,
        serverTimeoutObj: null,
        reset: function () {
            clearTimeout(this.timeoutObj);
            clearTimeout(this.serverTimeoutObj);
            return this;
        },
        start: function () {
            var self = this;
            this.timeoutObj = setTimeout(function () {
                //这里发送一个心跳,后端收到后,返回一个心跳消息,
                //onmessage拿到返回的心跳就说明连接正常
                that.websocket.send("Msg");
                //如果超过一定时间还没重置,说明后端主动断开了
                self.serverTimeoutObj = setTimeout(function () {
					//如果onclose会执行reconnect,我们执行socket.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                    that.websocket.close(); 
                }, self.timeout)
            }, this.timeout)
        }
    }


    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        console.log(innerHTML);
    }

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

后端代码

pom.xml依赖

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

新建配置类, 开启WebSocket支持:WebSocketConfig.java

/**
 * 开启WebSocket支持
 **/
@Configuration
public class WebSocketConfig {

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

}

新建WebSocketServer服务端:WebSocket.java

@ServerEndpoint(value = "/websocket")
@Component
public class WebSocket {

    /**
     * concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
     */
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<WebSocket>();


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


    
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
    }

    //TODO 给所有当前连接的用户发送消息
    public void sendAllToUserMessage(String message) {
        try {
            if (webSocketSet.size() != 0) {
                for (WebSocket item : webSocketSet) {
                    if (item != null) {
                        item.session.getBasicRemote().sendText(message);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //TODO 当浏览器关闭触发该事件
    @OnClose
    public void onClose(Session session) {
        webSocketSet.remove(this);
    }

    //接受前端发送的消息
    @OnMessage
    public void onMessage(String params, Session session1) {
        //params就是发送的消息根据自己的业务进行操作就可以了
    }

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

在线测试地址
http://www.jsons.cn/websocket/

连接地址为

ws://127.0.0.1:8080/换成自己的项目/websocket

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值