Receiving data with Stream
I'm sending data to a software, for remote controll it. My problem is, that when I send something and don't close inpuStream and outputStream, app is freezing. (maybe waiting for answer) When I send somethong and after that close inputStream and outputStream, I can't recive the answer, becouse the communication dialog is closed.
I'm creating a stream-pair with this method.
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)addr, port, &readStream, &writeStream);
NSInputStream *inputStream = (NSInputStream *)readStream;
NSOutp开发者_StackOverflow中文版utStream *outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
How can I solve this?
You most likely need to close only the output stream after you are done writing to it so the other side knows you are done, so it will write data that you can read on the input stream.
You can only start sending to an output stream if the stream:handleEvent: signals that the stream is ready to get your data for sending. Conversely if you try to read from a stream that did not signal that there are new bytes then this will also block.
I wrote DTBonjour for this kind of scenarios. You get a clean and simple API for connecting or publishing a service over WiFi. Then you just pass NSObjects to the connection and the recipient receives the decoded object. Couldn't be easier to use: http://www.cocoanetics.com/2012/11/and-bonjour-to-you-too/
精彩评论