Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: Socket Networking Fundamentals using CFStreamCreatePairWithSocketToHost

Use Case

I'm using sockets to send and receive data using CFStreamCreatePairWithSocketToHost() and am trying to wrap my head around how this is done when send multiple sets of data (i.e. not just 1 request).

Problem

Currently I can send data and receive a response (i.e. 1 round trip). However, after I send all the data in the outputStream the stream gets closed (i.e. receives NSStreamEventEndEncountered).

Question

So the question is, what happens when I want to send multiple data requests?

  • Do I setup a new socket every time I have a new data object to send?
  • Do I have to reset outputStream and send more data.

Code

Most of this code came from the Cocoa Streams Documentation:

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    _data = [[NSMutableData alloc] init];
    [self initNetworkCommunication];

    [self sendString:@"Hello World!"];
}

- (void)initNetworkCommunication {
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;

    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"123.456.0.0", 1234, &readStream, &writeStream);

    inputStream = (NSInputStream *)readStream; // ivar
    [inputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];

    outputStream = (NSOutputStream *)writeStream; // ivar
    [outputStream setDelegate:self];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream open];
}

- (void)sendString:(NSString *)string {
    NSData *data = [[NSData alloc] initWithData:[string dataUsingEncoding:NSASCIIStringEncoding]];
    [_data appendData:data];
    [data release];
}

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
    NSLog(@"stream event %u", streamEvent);

    switch (streamEvent) {
        case NSStreamEventOpenCompleted:
            NSLog(@"Stream opened");
            break;
        case NSStreamEventHasSpaceAvailable: {
            uint8_t *readBytes = (uint8_t *)[_data mutableBytes];
            readBytes += byteIndex; // ivar
            int data_len = [_data length];
            unsigned int len = ((data_len - byteIndex >= 1024) ? 1024 : (data_len - byteIndex));
            uint8_t buf[len];
            (void)memcpy(buf, readBytes, len);
            len = [(NSOutputStream *)theStream write:(const uint8_t *)buf maxLength:len];
            NSLog(@"Sending buffer of len: %d", len);
            byteIndex += len;
            break;
        }
        case NSStreamEventHasBytesAvailable:
            if (theStream == inputStream) {
                uint8_t buffer[1024];
                int len;

                while ([inputStream hasBytesAvailable]) {
                    len = [inputStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0) {
                        NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];

                        if (nil != output) {
                            NSLog(@"server said: %@", output);
                        }
                    }
                }

                [self sendString:@"Another Test"];
            }
            break;
        case NSStreamEventErrorOccurred:
            NSLog(@"Can not connect to the host!");
            break;
        case NSStreamEventEndEncountered:
            NSLog(@"Closing stream...");
            [theStream close];
            [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
            [theStream release];
            theStream = nil;
            break;
        default:
            NSLog(@"Unknown event");
    }
}

Response:

2012-08-15 08:16:30.896 Sockets[34836:f803] Opened input stream.
2012-08-15 08:16:30.898 Sockets[34836:f803] Opened output stream.
2012-08-15 08:16:30.899 Sockets[34836:f803] Sending buffer of len: 12
2012-08-15 08:16:30.900 Sockets[34836:f803] Sending buffer of len: 0
2012-08-15 08:16:30.901 Sockets[34836:f803] Closing output stream.
2012-08-15 08:16:30.939 Sockets[34836:f803] server said: Hello World!

Note the outputStream stream closes after I send the data. I try reinitiating outputStream before [self sendString:@"Another Test"];. I also tried idz's answer.

Per the documentation, I believe the Sending buffer of len: 0 is my problem.

If the delegate receives an NSStreamEventHasSpaceAvailable event and does not write anything to the stream, it does not receive further space-available events from the run loop until the NSOutputStream object receives more bytes. When this happens, the run loop is restarted for space-available events.

However, the documentation doesn't say anything about closing the stream when the end of the stream is reached. So I'm confused…

like image 773
Jason McCreary Avatar asked Aug 13 '12 19:08

Jason McCreary


1 Answers

A socket is a bidirectional stream connecting two programs, possibly on two different computers. It just transfers the data you write at one end to be read at the other end. It enforces no structure in the data and doesn’t know anything about requests or responses.

The CFStreamCreatePairWithSocketToHost API splits a single connection into two independent streams - one you can read from and one you can write to. This is a nice touch, the underlying socket API uses only one file descriptor both for reading and writing which can get quite confusing.

The connection stays open until one side closes the socket. There is also the possibility of shutting down the socket only in one direction. It is also possible to close the connection only in one direction. If the remote closes it’s read stream your write stream will be closed and vice versa.

Do I setup a new socket every time I have a new data object to send?

You should avoid doing that. It takes some time to establish a new connection, and it takes even more time before your connection gets to full speed. So you should reuse the same connection as much as possible.

Do I have to reset outputStream and send more data.

No, this is not necessary, just send more data.

Per the documentation, I believe the Sending buffer of len: 0 is my problem.

Writing nothing (that is a buffer of length 0) shouldn’t be a problem. The documentation doesn’t specify what will happen though. So I wrote I test program today to see what will happen, expecting nothing. As it turns out writing a buffer of length 0 closes the output stream. So this was really your problem. I will file a bug on the Apple Bug Reporter about that documentation issue, and so should you.

The part of the documentation you quoted is about something different. If you don’t write after you get a space available notification you won’t get another one until you have written something. That is useful, because so the system doesn’t waste CPU cycles to tell your code over and over again that you could write something if you don’t have anything to write.

like image 173
Sven Avatar answered Oct 06 '22 12:10

Sven