iosnetwork-programmingnsstreamcfstream

NSStream closing and opening error


I'm working with NSStream to send and receive single characters over a network connection.
I instantiate the streams both for reading and for writing using CFStreamCreatePairWithSocketToCFHost(...).

The basic working mechanism to send and receive is working fine.

Now I want to create the NSStream only when I need to send or receive something (usually one time every 2 minutes). The first time I create the streams, send the packet, close it and everything work well. Next I try to recreate the NSStream (create a new socket and open the stream on it), the opening function don't work. Since I'm using netcat to test it, I see that when I close the stream using [NSStream close] method, the connection on the server is not closing. How can I force to close the socket? Or there's a better way to do what I'm trying to do?


Solution

  • Use CFWriteStreamSetProperty and CFReadStreamSetProperty to set kCFStreamPropertyShouldCloseNativeSocket to kCFBooleanTrue in order that the underlying socket is closed when the stream is closed.