-1

I current writing a TCP socket using NSStream. I'm able to open the stream but i can't write out anything (eg. a NSString or NSData).

1 Answer 1

2

In your -stream:handleEvent: delegate method, when you receive an NSStreamEventHasSpaceAvailable event for the NSOutputStream, you can send data using:

NSData *data = /* get some data… */;
const uint8_t *buffer = [data bytes];
NSUInteger length = [data length];
NSInteger nwritten = [outputStream write:buffer maxLength:length];
if (-1 == nwritten) {
    NSLog(@"Error writing to stream %@: %@", outputStream, [outputStream streamError]);
} else {
    NSLog(@"Wrote %ld bytes to stream %@.", (long)nwritten, outputStream);
}
5
  • Hi, i have tried the code but i have got the error "error writing to stream <__NSCFOutputStream: 0x102009f0>: Error Domain=NSPOSIXErrorDomain Code=9 "The operation couldn’t be completed. Bad file descriptor" do anyone know the problem?
    – tan
    Oct 19, 2010 at 4:31
  • It sounds like it's not backed by a file descriptor. Did you open the stream? Are you trying to write from the delegate callback as described? Oct 19, 2010 at 4:50
  • Hi, i have used the following code to print out the streamStatus which returns a '2' so i guess the stream is open: NSLog(@"Status of outputStream: %i", [outputStream streamStatus]);
    – tan
    Oct 19, 2010 at 5:26
  • HasBytesAvailable is for reading. For writing, you need to check the NSStream delegate events to see if it has HasSpaceAvailable
    – xaphod
    Jan 21, 2015 at 21:33
  • @xapod : can you help me for the same issue? Jun 10, 2016 at 17:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.