Search code examples
iosobjective-csocketsnsstream

Connect to multiple servers at the same time using sockets in NSStream


I am creating a socket based iOS app using Objective-C, now my requirement is to connect to two servers at the same time.

I am using NSInputStream and NSOutputStream and I am able to connect to the first server as well as send and receive data with the server using the delegate method.

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent

How do I have connect with a second server at the same time or multiple servers at the same time?


Solution

  • You have two options, what you will typically do is create multiple instances of the class where you implemented the

    - (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent

    For instance you could have your own CustomConnection class with an init method like this:

    - (id)initWithUrl:(NSURL *)url

    But what you could also do (if you want to keep everything in one place) just test for the NSStream that is sending you the event:

    - (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
    {
       if(theStream == self.serverAInputStream)
       {
          //input from server a
       }
       if(theStream == self.serverBInputStream)
       // ... and so on!
    }