我目前在我的 appdelegate.m 中有一个 socketrocket 连接
_webSocket = [[SRWebSocket alloc] initWithURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"ws://pinkfalcon.nl:12345/connectr"]]];
_webSocket.delegate = self;
[_webSocket open];
以及对此的回应
- (void)webSocketDidOpen:(SRWebSocket *)webSocket;
{
[self.window makeKeyAndVisible];
NSLog(@"Websocket Connected");
}
我如何从另一个 View 请求该部分。我似乎找不到委托(delegate)函数来打开套接字火箭上的当前连接。我似乎找不到委托(delegate)函数的逻辑。
最佳答案
如果您的 _webSocket
ivar 作为您的 AppDelegate
的(希望是只读)属性提供,则可以从代码中的其他位置检查套接字的状态:
if ([UIApplication sharedApplication].delegate.webSocket.readyState == SR_OPEN) {}
列举了不同的状态here .更好的方法是将此类检查封装到 AppDelegate
中的 - (BOOL)socketIsOpen
或 - (BOOL)socketIsClosed
等方法中。
此外,如果您希望套接字打开触发应用程序的其他操作,您可能需要使用类似 NSNotificationCenter
的东西,这样应用程序的任何部分都可以在套接字打开时收到通知,以及关闭时:
- (void)webSocketDidOpen:(SRWebSocket *)webSocket {
// your existing code
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotificationName:@"myapp.websocket.open" object:webSocket];
}
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code
reason:(NSString *)reason
wasClean:(BOOL)wasClean; {
// your code
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center postNotificationName:@"myapp.websocket.close"
object:webSocket
userInfo:@{
@"code": @(code),
@"reason": reason,
@"clean": @(wasClean)
}];
}
这将允许应用程序的其他部分执行以下操作:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(socketDidOpen:)
name:@"myapp.websocket.open"
object:nil];
其中 socketDidOpen:
将采用单个 NSNotification*
参数。
不过,作为一般建议,您不应等待 Websocket 连接打开才使 UIWindow 键可见,因为如果没有可用连接,这将使您的用户无法使用您的应用程序。在一般情况下,连接设置应在后台管理,并与设置应用程序 UI 异步。
关于ios - SocketRocket 调用打开的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17319506/