紧接这一篇
在使用socket进行通信之前我们首先来认识几个东东:
CFReadStreamRef
CFWriteStreamRef
来看看水果公司官方的解释:
CFReadStream
provides an interface for reading a byte stream either synchronously or asynchronously. You can create streams that read bytes from a block of memory, a file, or a generic socket。
CFStream是一个输入输出数据流,可以实现和内存、文件、socket之间的数据交互。因此我们这里使用Socket必然要使用这个对象。
再来看看另外两个对象:
NSInputStream
NSOutputStream
NSStream
is an abstract class for objects representing streams. Its interface is common to all Cocoa stream classes, including its concrete subclasses NSInputStream
and NSOutputStream
.
这个对象实现了和底层数流的交互,可以和CFStream实现无阻碍连接。
socket实现网络通信主要由两个方法组成:
- (void)initNetworkCommunication
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
// 建立与服务器的连接,设置ip地址,PORT端口,返回输入输出数据流。
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.1.134",PORT, &readStream, &writeStream);
// __bridge_transfer 一般用于将core foundation转化为foundation
_inputStream = (__bridge_transferNSInputStream *)readStream;
_outputStream = (__bridge_transferNSOutputStream