文档详情

ios开发之iOS Socket 开发.docx

发布:2017-05-27约1.14万字共2页下载文档
文本预览下载声明
ios开发之iOS Socket 开发 这个类使用了Singleton,因此永远只有一个实例。没有实例时会自动生成实例,可以在程序中的任何位置调用它。? 一般来说,只要跟服务器建立一次连接即可,产生一对stream,分别是outStream和inStream,所有的数据都通过它们不断地发送和接收。 stream的end意味着连接中断,如果还需要访问服务器的话,得重新连接stream。(也就是重新实例化一下我这个类) 每次发送和接受的数据包大小需要自己控制,而不是等stream来告诉你这个数据包有多大,因为stream不会告诉你…… 控制方法之一:通过添加一个特殊的后缀来判断,比如“EOF”,每次读到这个组合就认为数据读完。但是问题很明显,这个只能用于string。 控制方法之二:通过添加一个4字节的前缀来判断长度。这4个byte的byte[]数组,是当前数据包的长度信息,根据这个信息来读取一定长度的数据。 每次数据收完后,我用了一个取巧的方法来把数据返还给调用stream的函数……这个部分需要改进。 SynthesizeSingleton.h,实现singleton的类 // //??SynthesizeSingleton.h //??CocoaWithLove // //??Created by Matt Gallagher on 20/10/08. //??Copyright 2009 Matt Gallagher. All rights reserved. // //??Permission is given to use this source code file without charge in any //??project, commercial or otherwise, entirely at your risk, with the condition //??that any redistribution (in part or whole) of source code must retain //??this copyright and permission notice. Attribution in compiled projects is //??appreciated but not required. // ? #define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) static classname *shared##classname = nil; + (classname *)shared##classname { ? ? @synchronized(self) ? ? { ? ?? ???if (shared##classname == nil) ? ?? ???{ ? ?? ?? ?? ?shared##classname = [[self alloc] init]; ? ?? ???} ? ? } ? ??? ? ? return shared##classname; } + (id)allocWithZone:(NSZone *)zone { ? ? @synchronized(self) ? ? { ? ?? ???if (shared##classname == nil) ? ?? ???{ ? ?? ?? ?? ?shared##classname = [super allocWithZone:zone]; ? ?? ?? ?? ?return shared##classname; ? ?? ???} ? ? } ? ??? ? ? return nil; } - (id)copyWithZone:(NSZone *)zone { ? ? return self; } - (id)retain { ? ? return self; } - (NSUInteger)retainCount { ? ? return NSUIntegerMax; } - (void)release { } - (id)autorelease { ? ? return self; } 复制代码 Stream.h #import Foundation/Foundation.h?? #
显示全部
相似文档