0

I know that you can create a NSInputStream and NSOutputStream pair (toll-free bridged to CFReadStream, CFWriteStream) by opening a TCP client connection using CFStreamCreatePairWithSocketToHost according to the Stream Programming Guide.

How can one create a TCP server that listens on a port and accepts a connection as a NSInputStream and NSOutputStream pair?

4

2 回答 2

1

The RemoteCurrency sample project provides an example of this in QServer.m (previously known as TCPServer.m). The sample code is actually for setting up Bonjour advertising, but that part can be excluded for a simple TCP server.

You create a socket with your own accept callback by calling CFSocketCreate, bind and listen to a port by calling CFSocketSetAddress, and start getting accept callbacks by calling CFSocketCreateRunLoopSource followed by CFRunLoopAddSource.

Then, in the accept callback, you create NSInputStream/NSOutputStream pair from the connection handle using CFStreamCreatePairWithSocket, set the input stream’s delegate and start receiving recv callbacks by calling scheduleInRunLoop:forMode:, and then open both streams to start using them.

Using NSInputStream and NSOutputStream abstractions (as opposed to creating a new thread and calling the standard UNIX functions socket, bind, listen, accept, send, recv) allows one to easily receive network events in the same NSRunLoop as the rest of the run-loop based APIs on OSX.

于 2014-02-07T22:59:44.677 回答
0

I have a sample app that you can download that creates a pair of NSStreams connected through a socket. It then streams picture-perfect, real-time video through the sockets using the camera on an iOS device:

The code is concise, and simple-to-follow (ignore the extra files in the project; NavController.h/m and PeerConnectionViewController.h/m and CameraViewController.h/m are the only three files of relevance):

https://app.box.com/s/fnim5ril4mzu518wj98zy3ah8l83jayv

于 2017-09-21T23:17:47.813 回答