dimanche 2 août 2015

reusing socket read and write stream objects

I'm following this tutorial on building a chat app in ios. The tutorial uses the same view controller for both the "log in" view, and the "chat room" view. I don't like this, and would rather use two separate view controllers.

The issue with this is that the objects I use to create a connection with my server are on the first viewController class, but I need to use them on my second viewController class so I can send and receive chat messages without having to re-connect.

what options do I have for this? Is there a way to reconnect to the server without the server seeing it as a new connection? Or can I reuse the same streamReader and streamWriter in my second view controller?

this is the method that establishes a connection:

- (void)initNetworkCommunication {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 8080, &readStream, &writeStream);
    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];
}

Aucun commentaire:

Enregistrer un commentaire