1

我需要 IOS Socket 编程方面的帮助。我已经在 IOS 和 Java 服务器之间实现了一个成功的 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?

先感谢您!!

4

1 回答 1

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];
}  

我发现这个库很容易使用。我希望这对任何人都有帮助。非常感谢。

于 2012-05-29T11:15:10.383 回答