How to check if a network socket is active or not using SRWebsocket

I am using SRWebsocket for socket connection. Now I call the open open function when the application comes to the fore, but I don't want to do that. I need to check first if the connection is active or not and only open the websocket. Is there a way to do this?

- (void)connectWebSocket {


if( self.readyState == SR_OPEN){

    NSLog(@"CONNECT%u ",self.readyState);
} else {

    NSLog(@"CLOSED %u",self.readyState);

}





[[IXDataBaseManager sharedNetworkDataManager] deleteOldPolls];


NSString *urlString =@"wss://m.hol.com/testing/api/ws/"; 



if( self.webSocket ) {
    [self.webSocket close];
    self.webSocket.delegate = nil;
    self.webSocket=nil;
}
self.webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] protocols:@[@"hol-json"]];
self.webSocket.delegate = self;
[self.webSocket open];
NSLog(@"CONNECTOPN%u ",self.readyState);

}

      

self.readyState always returns "0"

+3


source to share


1 answer


Maybe this sample code will help you:



- (void)openSocket {
    if (_webSocket.readyState == SR_CLOSED)
    {
        // _websocket is closed. Open your web socket again
        [_webSocket open];
    } else {
        // _websocket is not closed. check the readyState and perform your task accordingly
    }
}

- (void)forceOpenSocket {
    _webSocket.delegate = nil;
    [_webSocket close];

    _webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"Input Url"]]];
    _webSocket.delegate = self;

    // Opening Connection ...
    [_webSocket open];
}

      

+1


source







All Articles