React reconnecting-websocket的使用

本文介绍了使用`reconnecting-websocket`库在JavaScript中安装、引入及建立WebSocket连接的方法。当连接出现错误或关闭时,代码会触发重新连接,并设置定时发送心跳消息。在接收到错误或关闭事件时,如果存在授权信息,会尝试重新建立连接。
摘要由CSDN通过智能技术生成

1:安装方式: cnpm i reconnecting-websocket
2:引入:import ReconnectingWebSocket from 'reconnecting-websocket';
3:连接websocket

GOD.SOCKET = new ReconnectingWebSocket(wsUrl);
GOD.SOCKET.addEventListener('open', () => {
    GOD.SOCKETTimer = setInterval(() => {
        if (GOD.SOCKET) {
            GOD.SOCKET.send('0')
        }
    }, 30000);
});

GOD.SOCKET.addEventListener('error', (e) => {
    console.log('WS错误:' + e.code + ' ' + e.reason + ' ' + e.wasClean);
    const authorization = sessionStorage.getItem('authorization');
    if (authorization) {
        WSLink();
    }
});

GOD.SOCKET.addEventListener('close', (e) => {
    console.log('WS断开:' + e.code + ' ' + e.reason + ' ' + e.wasClean);
    const authorization = sessionStorage.getItem('authorization');
    if (authorization) {
        WSLink();
    }
});

GOD.SOCKET.addEventListener('message', (socket) => {
        const result = JSON.parse(socket.data);
        const {projectId, code, tabsId, type, from, errMsg, timestamp} = result
})
Spring Boot Starter Websocket是一个轻量级的启动器,用于快速集成WebSocket支持到你的Spring Boot应用中。在客户端使用它,你可以利用Spring框架提供的WebSocket API,例如`org.springframework.web.socket`包下的类,如`TextMessage`、`BinaryMessage`和`WebSocketSession`。 以下是基本步骤: 1. 添加依赖:在你的`pom.xml`或`build.gradle`文件中添加Spring WebSocket的依赖,对于Maven示例: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency> ``` 2. 创建WebSocket配置:如果需要自定义WebSocket处理器,可以在Application中创建一个`WebSocketHandler`,并注册它到`WebSocketTransportRegistration`: ```java @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/websocket").withSockJS(); } } ``` 3. 客户端连接:在JavaScript(常常通过Angular或React)中,使用`WebSocket`对象创建连接,比如: ```javascript const socket = new WebSocket('ws://your-app-url/websocket'); ``` 然后可以发送消息、接收事件等操作。 4. 发送和接收消息:客户端可以使用`send()`方法发送消息,监听`message`事件来处理服务器发来的消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值