IOS AsyncSocket

导入AsyncSocket.h  AsyncSocket.m   AsyncUdpSocket.h   AsyncUdpSocket.m   以及  CFNetWork.framework   

 

 

asyncSocket = [[AsyncSocketalloc] initWithDelegate:self];

    NSError *err = nil;

    if(![asyncSocketconnectToHost:@"www.baidu.com"onPort:80error:&err])

    {

        NSLog(@"Error: %@", err);

    }

    

    

    [asyncSocketwriteData:[@"GET / HTTP/1.1\n\n"dataUsingEncoding:NSUTF8StringEncoding] withTimeout:3tag:1];

 

 

 

 

 

 

//建立连接

-(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port

{

    NSLog(@"onScoket:%p did connecte to host:%@ on port:%d",sock,host,port);

    [sock readDataWithTimeout:1tag:0];

}

 

//读取数据

-(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag

{

    NSString *aStr=[[NSStringalloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"aStr==%@",aStr);

    

    

    NSData *aData=[@"Hi there"dataUsingEncoding:NSUTF8StringEncoding];

    [sock writeData:aData withTimeout:-1 tag:1];

    [sock readDataWithTimeout:1tag:0];

}

 

//是否加密

-(void)onSocketDidSecure:(AsyncSocket *)sock

{

    NSLog(@"onSocket:%p did go a secure line:YES",sock);

}

 

//遇到错误时关闭连接

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

{

    NSLog(@"onSocket:%p will disconnect with error:%@",sock,err);

}

 

//断开连接

-(void)onSocketDidDisconnect:(AsyncSocket *)sock

{

    NSLog(@"onSocketDidDisconnect:%p",sock);

}

 

你可能感兴趣的:(socket)