我发现从未调用过委托,因为 websocket 从未真正关闭过。SRWebSocket 中 websocket 的关闭发生在 pumpWriting 方法中,如下所示:
if (_closeWhenFinishedWriting &&
_outputBuffer.length - _outputBufferOffset == 0 &&
(_inputStream.streamStatus != NSStreamStatusNotOpen &&
_inputStream.streamStatus != NSStreamStatusClosed) &&
!_sentClose) {
_sentClose = YES;
[_outputStream close];
[_inputStream close];
if (!_failed) {
dispatch_async(_callbackQueue, ^{
if ([self.delegate respondsToSelector:@selector(webSocket:didCloseWithCode:reason:wasClean:)]) {
[self.delegate webSocket:self didCloseWithCode:_closeCode reason:_closeReason wasClean:YES];
}
});
}
_selfRetain = nil;
NSLog(@" Is really closed and released ");
}
else {
NSLog(@" Is NOT closed and released ");
}
所有流和保留 websocket 的对象都在此处关闭或删除。只要它们仍然打开,套接字就不会适当地关闭。但是关闭在我的程序中从未发生过,因为当我试图关闭 websocket 时,_closeWhenFinishedWriting总是 NO。
此布尔值仅在断开连接方法中设置一次。
- (void)_disconnect;
{
assert(dispatch_get_current_queue() == _workQueue);
SRFastLog(@"Trying to disconnect");
_closeWhenFinishedWriting = YES;
[self _pumpWriting];
}
但是在SRWebSocket中调用closeWithCode方法时,disconnect只在一种情况下调用,即websocket处于连接状态。
BOOL wasConnecting = self.readyState == SR_CONNECTING;
SRFastLog(@"Closing with code %d reason %@", code, reason);
dispatch_async(_workQueue, ^{
if (wasConnecting) {
[self _disconnect];
return;
}
这意味着,如果套接字处于另一种状态,则 websocket 永远不会真正关闭。一种解决方法是始终调用断开连接方法。至少它对我有用,一切似乎都很好。
如果有人知道为什么 SRWebSocket 是这样实现的,请对此答案发表评论并帮助我。