Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8412609
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T00:42:55+00:00 2026-06-10T00:42:55+00:00

Use Case I’m using sockets to send and receive data using CFStreamCreatePairWithSocketToHost() and am

  • 0

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…

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T00:42:57+00:00Added an answer on June 10, 2026 at 12:42 am

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Use case: I'm using data templates to match a View to a ViewModel. Data
the use case that I'm concerned with in this post involves iterating over a
My use case is as follows -- I have a database table with around
My use case is this, I want to call out to a webservice and
My Use case like this - User is in my application - User presses
Use case: we have some project meta-data files which we want tracked, but are
My Use Case: my Hibernate configuration using auto increment generator for insert and I
Consider this use case scenario: I wish to auto complete and provide the skeleton
This use case seems like it would apply to just about every form, but
I have the following use case, my file contents look like this a b

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.