我正在使用https://github.com/pkyeck/socket.IO-objc基于iOS7的socket.io-obj库,但我发现当套接字因网络环境不良而断开服务器时,我的应用程序会挂起很长时间。 这是我的代码:
#define NOTE_CENTER [NSNotificationCenter defaultCenter]
-(void)connectServer
{
[socketIO connectToHost:SOCKETADDRESS
onPort:SOCKETPORT
withParams:nil
];
status = Connecting;
NSLog(@"%@",socketIO.debugDescription);
[[] postNotificationName:kConnectingServer object:nil];
}
-(void)disConnectServer
{
[socketIO disconnect];
}
-(BOOL)hasConnected {
if (status==Connected) {
return true;
}
return false;
}
-(NetworkStatus)networkStatus
{
return status;
}
-(void) sendEvent:(OrderEvent)eventIndex withData:(NSDictionary *)data
{
if (status==Connected) {
[socketIO sendEvent:@"close" withData:data];
//[socketIO sendEvent:[NSString stringWithFormat:@"%lu",eventIndex] withData:data];
}
}
-(void) sendEventWithName:(NSString*)eventName withData:(NSDictionary *)data
{
if (status==Connected) {
[socketIO sendEvent:eventName withData:data];
}
}
#pragma socketIO Delegate methods
- (void) socketIODidConnect:(SocketIO *)socket
{
status = Connected;
[NOTE_CENTER postNotificationName:kConnectedServer object:nil];
}
- (void) socketIODidDisconnect:(SocketIO *)socket disconnectedWithError:(NSError *)error
{
status = OffLine;
NSLog(@"socket.io disconnected. did error occur? %@", error);
[NOTE_CENTER postNotificationName:kDisConnectedServer object:nil];
}
- (void) socketIO:(SocketIO *)socket onError:(NSError *)error
{
[socket disconnectForced];
[NOTE_CENTER postNotificationName:kConnecteServerError object:nil];
if ([error code] == SocketIOUnauthorized) {
NSLog(@"not authorized");
} else {
NSLog(@"onError() %@", error);
}
}
- (void) socketIO:(SocketIO *)socket didReceiveJSON:(SocketIOPacket *)packet
{
}
- (void) socketIO:(SocketIO *)socket didReceiveEvent:(SocketIOPacket *)packet
{
NSLog(@"didReceiveEvent()");
// test acknowledge
NSString *packName = [packet name];
//if (packet.name) {
[NOTE_CENTER postNotificationName:packName object:nil userInfo:[[NSDictionary alloc] initWithObjectsAndKeys:[packet data],@"data", nil]];
//}
/*
SocketIOCallback cb = ^(id argsData) {
NSDictionary *response = argsData;
// do something with response
NSString *packetName = [response stringValueForKey:@"name"];
[NOTE_CENTER postNotificationName:packetName object:nil userInfo:response];
};*/
}
我发生的另一个问题是当我调用“[socketIO disconnect]”时,服务器不会立即断开我的应用程序。请帮我找到这些问题的答案。
非常感谢。
答案 0 :(得分:0)
对于迟到的回复我很抱歉。我发现如果你的socket.io服务器在尝试 disconnectForced 时关闭,那么UI将会阻塞,因为如果你看一下这个方法,请求是使用 sendSynchronousRequest
您可以尝试修改方法以使用 sendAsynchronousRequest ,但我建议您进一步检查该类。您还可以在使用 disconnectForced 之前检查连接状态。