IOS中的套接字断开连接

时间:2012-05-25 18:31:48

标签: objective-c ios sockets tcp

我在IOS Socket编程中需要一些帮助。我已经在IOS和Java Server之间实现了一个成功的TCP Socket连接,但是我发现在套接字失败后重新连接它是不可能的(我断开网络连接并重新连接)。

这是我用来打开流的代码:

- (void)initCommunication{
@try {
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"XXX.XXX.XXX.XXX", 4454, &readStream, &writeStream);

    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;

    //Asignamos los delegates
    inputStream.delegate = self;
    outputStream.delegate = self;  

    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [inputStream open];
    [outputStream open];
    connected = true;
    }
}
@catch (NSException *exception) {
    connected = false;
    NSLog(@"Error connecting socket: %@", exception.reason);
    [self checkConnection];
}
}

当我收到NSStreamEventErrorOccurred或NSStreamEventEndEncountered时,我尝试关闭连接并重新连接。

我关闭它:

-(void) close{

[inputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream close];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream setDelegate:nil];
inputStream = nil;
[outputStream setDelegate:nil];
outputStream = nil;

connected = false;
}

问题是套接字没有再次重新连接...我正在考虑使用SmallSockets或CocoaAsyncSockets来查看我是否可以重新连接套接字...你看到任何实现问题吗?您是否建议使用SmallSockets或CocoaAsyncSockets?

提前谢谢!!

1 个答案:

答案 0 :(得分:3)

最后我用CocoaAsyncSockets https://github.com/robbiehanson/CocoaAsyncSocket实现了它,并且很容易与这个套接字重新连接。

首先我初始化套接字对象:

socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];

连接我使用:

NSError *err = nil;
if ([socket connectToHost:@"XXX.XXX.XXX.XXX" onPort:YYYY error:&err])
{
NSLog(@"Connection performed!");
}
else
{
NSLog(@"Unable to connect: %@", err);
}

然后,只要失败,您就可以使用委托进行重新连接:

- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
NSLog(@"Socket:DidConnectToHost: %@ Port: %hu", host, port);

connected = YES;
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
NSLog(@"SocketDidDisconnect:WithError: %@", err);   
    connected = NO;
    //We will try to reconnect
    [self checkConnection];
}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    [self processReceivedData:data];
    [sock readDataWithTimeout:-1 tag:0];
}  

我发现很容易使用该库。我希望能帮助任何人。 非常感谢。