I’m trying to use the stream object (input/output) to communicate with a server.
But I’m not sure if I’m doing this well, or if I have to adapt what I’ve already done.
At the moment in each view whom need to communicate with my server I’m openning a connection with this method :
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)kServerIp, kServerPort, &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];
}
And I don’t know if it’s the right way to do it (I’m pretty sure it’s not). I’m also using JSON to communicate with my server (and again I don’t know if the best way to do that, if it’s not let me know)
So I’m wondering if you guys can teach me the right way to use stream object 🙂
I’ve found this post Manage sockets in iOS with uitabbarcontroller but I don’t really understand what I’ve to do.
p.s. I’m using stream to do queries on my database i.e. : app -> giveMeMyNews -> server -> yourNews -> app -> Display. Pretty simple but again since I’m really new to iPhone developpement I don’t know if I’m doing this right 🙁
Streams are working such that you can either have an input stream or output stream. The stream sends a delegate method when it is able to accept your bytes for sending or when there a new bytes available that where received.
Have a look at my Bonjour writeup how I implemented the stream:handleEvent: method, that should clear things up: http://www.cocoanetics.com/2012/11/bonjour/
Finally if you are looking to communicate via WiFi between iOS and/or Mac devices I wrote DTBonjour which greatly simplifies sending of objects. You connect and send NSObjects, they automatically get encoded as plist or json and the recipient gets it as decoded object. http://www.cocoanetics.com/2012/11/and-bonjour-to-you-too/
In the least I believe that my code is sufficiently clear to help you understand the process.