簡體   English   中英

如果以接受方式斷開/連接 Web 套接字,則 WebSocket 不會重新連接

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

在我的應用程序中,當用戶登錄時,我創建了帶有會話 ID 的 webSocket 連接。 並在注銷后套接字將關閉。 這工作正常。 但是,如果我注銷並在殺死應用程序之前再次使用相同帳戶或不同帳戶登錄 webSocket 拋出錯誤現在received bad response code from server 503 , 如果注銷后殺死應用程序並使用初始渲染和用戶登錄套接字打開應用程序將連接沒有任何錯誤。 我的套接字代碼如下。 在這方面的任何幫助將不勝感激。

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);

wireshark的幫助下調試幾個小時后,我開始知道在我的用例中有一對cookie在注銷時發送到服務器,但沒有清除cookie。 所以首先清除cookie然后重新連接服務器。

在此處輸入圖片說明

只需在使用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