首先导入CFNetwork.framework框架

1、下载ASyncSocket库源码
 
2、把ASyncSocket库源码加入项目
 
3、在项目增加CFNetwork框架

使用AsyncSocket开源的框架可以很方便的与其它系统进行Socket通信, AsyncSocket包括TCP和UDP,

通过实现委托AsyncSocketDelegate进行交互。AsyncSocketDelegate有如下消息调用。

 @implementation SocketComm

 //初始话,创建socket
- (id) init
{
self = [super init];
if (self != nil) {
_sock = [[AsyncSocket alloc] initWithDelegate:self];
[_sock setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; }
return self; }
 

即将连接及发生错误会调用willDisconnectWithError

 - (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err{

     [_asyncSocket release];

     _asyncSocket = nil;

 }
其它方法调用:
1 - (void)onSocketDidDisconnect:(AsyncSocket *)sock;
//收到新的socket连接时调用
- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket; - (NSRunLoop *)onSocket:(AsyncSocket *)sock wantsRunLoopForNewSocket:(AsyncSocket *)newSocket; - (BOOL)onSocketWillConnect:(AsyncSocket *)sock;

网络连接成功后,调用didConnectToHost, 收发数据中必须添加 [sock readDataWithTimeout:-1 tag:0];否则接收不到数据,

并且这个函数在数据返回就必须调用一次,让他一直循环下去

//异步返回的连接成功
1 - (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
2 { [sock readDataWithTimeout:- tag:]; }
   //读取客户端发送来的信息
1 - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{ NSString *msg = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease]; if(msg)
{ //处理受到的数据 }
else
{ NSLog(@"Error converting received data into UTF-8 String"); } [sock readDataWithTimeout:- tag:]; }
 - (void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;

 - (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag;

 - (void)onSocket:(AsyncSocket *)sock didWritePartialDataOfLength:(NSUInteger)partialLength tag:(long)tag;

 - (NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutReadWithTag:(long)tag 
elapsed:(NSTimeInterval)elapsed bytesDone:(NSUInteger)length; - (NSTimeInterval)onSocket:(AsyncSocket *)sock shouldTimeoutWriteWithTag:(long)tag
elapsed:(NSTimeInterval)elapsed
bytesDone:(NSUInteger)length; - (void)onSocketDidSecure:(AsyncSocket *)sock;

AsyncSocket包括connectToHost,writeData,readDataWithTimeout等基本调用,发送这些消息,会触发相应Delegate相应的方法。

05-26 19:11