问题
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?
回答1:
Use CFWriteStreamSetProperty
and CFReadStreamSetProperty
to set kCFStreamPropertyShouldCloseNativeSocket
to kCFBooleanTrue
in order that the underlying socket is closed when the stream is closed.
来源:https://stackoverflow.com/questions/16592873/nsstream-closing-and-opening-error