简体   繁体   中英

WebSocket not reconnect if disconnect/connect Web socket receptively

In my application when User Login I create webSocket connection with session ID. 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. 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. so first clear the cookie then reconnect with the server.

在此处输入图片说明

Just clear the all cookies before reconnecting to the server using cookies

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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