当再次打开套接字时,发生`NSStreamEventEndEncountered`事件并与`SRWebSocket`崩溃

时间:2016-01-25 07:36:16

标签: ios objective-c sockets websocket

我在客户端应用程序与一个远程服务器之间建立套接字,使用单个SRWebSocket实例,以便在远程服务器和我的客户端应用程序之间及时传输数据。我将初始化它并在用户登录时打开流并进入主页。

+ (WebSocket*)shared:(NSString *)server
{
    if (instance == nil || ![server isEqualToString:instance.nodeServer]) {
        instance = [[WebSocket alloc] init];
        topicQueue = [NSMutableArray array];
    }
    instance.nodeServer = server;
    return instance;
}

WebSocketSRWebSocket的封装,并处理SRWebSocket的委托选择器。

self.socket = [[SRWebSocket alloc] initWithURL:request protocols:supportedProtocols];
[_socket setDelegate:self];

当我第一次创建流并调用[socket open]时,一切正常,它会获取事件NSStreamEventHasBytesAvailableNSStreamEventHasSpaceAvailableNSStreamEventOpenCompleted。我的客户端应用程序与远程服务器之间的流运行良好。

open的实施如下:

- (void)open;
{
    assert(_url);
    NSAssert(_readyState == SR_CONNECTING && _inputStream == nil && _outputStream == nil, @"Cannot call -(void)open on SRWebSocket more than once");

    _selfRetain = self;

    NSInteger port = _url.port.integerValue;
    if (port == 0) {
        if (!_secure) {
            port = 80;
        } else {
            port = 443;
        }
    }

    [self _connectToHost:_url.host port:port];
}

但是,我的客户端应用程序因为我不知道的事情而获得了事件NSStreamEventEndEncountered。并调用NSStreamEvents的委托选择器如下:

case NSStreamEventEndEncountered: {
     [self _pumpScanner];
     SRFastLog(@"NSStreamEventEndEncountered %@", aStream);
     if (aStream.streamError) {
         [self _failWithError:aStream.streamError];
     } else {
         if (self.readyState != SR_CLOSED) {
             self.readyState = SR_CLOSED;
             _selfRetain = nil;
         }

         if (!_sentClose && !_failed) {
              _sentClose = YES;
             // If we get closed in this state it's probably not clean because we should be sending this when we send messages
             dispatch_async(_callbackQueue, ^{
                 if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) {
                     [self.delegate webSocket:self didCloseWithCode:0 reason:@"Stream end encountered" wasClean:NO];
                 }
             });
         }
     }

    break;
}

套接字的状态已关闭但流不是零。当用户从登录页面进入我的客户端应用程序中的主页时,再次调用[socket open]。但是这个断言是错误的,NSAssert(_readyState == SR_CONNECTING && _inputStream == nil && _outputStream == nil, @"Cannot call -(void)open on SRWebSocket more than once");

我认为在收到事件socket时将NSStreamEventEndEncountered分配给nil但是会初始化一个新的套接字和流,这在我看来是不好的。

如果您知道错误或者您有更好的方法,请帮助我!

我在stack overflow中搜索了几个问题以及答案,但对我没什么用。

0 个答案:

没有答案