iOS how to register selector as a stream event callback?

832 views Asked by At

I want to create a TCP connection between iPhone and PC.

So I'm creating two CFStreamRef-s and i want to register my object selector to be called when new bytes are available for reading.

http://developer.apple.com/library/mac/#documentation/Networking/Conceptual/CFNetwork/CFStreamTasks/CFStreamTasks.html#//apple_ref/doc/uid/TP30000230-62008

As I understood from the link above I can register a function for a read stream like this

CFReadStreamSetClient(myReadStream, registeredEvents, myCallBack, &myContext)

Can I register a selector of my object like this ?

3

There are 3 answers

0
Andrew On BEST ANSWER

CFReadStreamRef is just a NSInputStream.

-(void) tryToConnect
{
    CFReadStreamRef myReadStream = NULL;
    CFWriteStreamRef myWriteStream = NULL;

    // Create socket.
    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
                                   (CFStringRef) ip_,
                                   port_,
                                   &myReadStream,
                                   &myWriteStream);
    //TODO: check if everything is ok

    readStream_ = (NSInputStream*) myReadStream;
    writeStream_ = (NSOutputStream*) myWriteStream;

    [readStream_ setDelegate:self]; //register to get events
    [readStream_ scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

    [readStream_ open];
    [writeStream_ open];
    [self sendSomething];
}

Everything you have to do more is implement NSStreamDelegate

0
Shiva Reddy On

For establishing the TCP Connection between iPhone and PC refer this link

http://xmppframework.googlecode.com.

Its actually developed for mac there is also an iPhone version, please go thorough it once.

0
Felix On

Check out this asynchronous socket networking library:

http://code.google.com/p/cocoaasyncsocket/

AsyncSocket is a object-oriented wrapper for CFSocket and CFStream and supports TCP and UDP.