建立到服务器的连接
在Mac OS X上,可以使用NSHost和NSStream对象建立到服务器的连接。
NSStream类有一个方法getStreamsToHost:port:inputStream:outputStream:,它创建一个到服务器的输入和输出流,但问题是iPhone OS不支持getStreamsToHost:port:inputStream:outputStream:方法。为了想使用这个方法,你可以增加一个类别到现有的NSStream类上,替换getStreamsToHost:port:inputStream:outputStream:方法提供的功能。
在NSStreamAdditions.h文件中,增加下面的代码:
@implementation NSStream (MyAdditions)+ (void)getStreamsToHostNamed:(NSString *)hostName port:(NSInteger)port inputStream:(NSInputStream **)inputStreamPtr outputStream:(NSOutputStream **)outputStreamPtr {CFReadStreamRef readStream;CFWriteStreamRef writeStream;assert(hostName != nil);assert((port > 0) && (port < 65536));assert((inputStreamPtr != NULL) || (outputStreamPtr != NULL));readStream = NULL;writeStream = NULL;CFStreamCreatePairWithSocketToHost( NULL, (CFStringRef)hostName, port, ((inputStreamPtr != nil) ? &readStream : NULL), ((outputStreamPtr != nil) ? &writeStream : NULL));if (inputStreamPtr != NULL) {*inputStreamPtr = [NSMakeCollectable(readStream) autorelease];}if (outputStreamPtr != NULL) {*outputStreamPtr = [NSMakeCollectable(writeStream) autorelease];}}@end