简体   繁体   English

如果以接受方式断开/连接 Web 套接字,则 WebSocket 不会重新连接

[英]WebSocket not reconnect if disconnect/connect Web socket receptively

In my application when User Login I create webSocket connection with session ID.在我的应用程序中,当用户登录时,我创建了带有会话 ID 的 webSocket 连接。 and after logout socket will close.并在注销后套接字将关闭。 This is working fine.这工作正常。 But if I logout and before killing the App if again login either with same account or with different account webSocket throwing error received bad response code from server 503 now if I killed the App while user is login now when I start the App WebSocket will connect perfectly, also if after logout if killed the App and open the App with initial render and user login socket will connect without any error.但是,如果我注销并在杀死应用程序之前再次使用相同帐户或不同帐户登录 webSocket 抛出错误现在received bad response code from server 503 , 如果注销后杀死应用程序并使用初始渲染和用户登录套接字打开应用程序将连接没有任何错误。 MY Socket code is below.我的套接字代码如下。 Any help in this regard will be highly appreciated.在这方面的任何帮助将不胜感激。

import React, {Component} from 'react';
import {connect} from 'react-redux';
class SocketController extends React.PureComponent {

    state = {
        socket: null
    }

    closeSocket() {
        this
            .state
            .socket
            .close();
        this.setState({socket: null})
    }
    componentDidUpdate() {
        if (this.props.user && this.props.user.sessionId) {
            this.connectSocket();
        } else {
            this.closeSocket()
        }
    }

    connectSocket() {
        let url = 'ws://localhost/socket';
        this.setState({
            socket: new WebSocket(url, '', {
                headers: {
                    Cookie: this.props.user.sessionId
                }
            })
        }, () => {

            this.state.socket.onerror = (e) => {
                console.log(e.message);
            }

            this.state.socket.onclose = () => {}
            this.state.socket.onopen = (e) => {}
            this.state.socket.onmessage = (event) => {}

        });

    }
    render() {
        return null
    }

}

const mapStateToProps = ({user}) => ({user});

export default connect(mapStateToProps)(SocketController);

After several hour of debugging with the help of wireshark I came to know in my usecase there is pair of cookie sending to the server on logout there is not clearing the cookies.wireshark的帮助下调试几个小时后,我开始知道在我的用例中有一对cookie在注销时发送到服务器,但没有清除cookie。 so first clear the cookie then reconnect with the server.所以首先清除cookie然后重新连接服务器。

在此处输入图片说明

Just clear the all cookies before reconnecting to the server using cookies只需在使用cookie重新连接到服务器之前清除所有cookie

import CookieManager from '@react-native-community/cookies';

// clear cookies
   CookieManager.clearAll()
      .then((success) => {
        console.log('CookieManager.clearAll =>', success);
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM