GCDAsyncSocket的使用

//
//  AppDelegate.m
//  test
//
//  Created by wup on 15/5/25.
//  Copyright (c) 2015年 apple. All rights reserved.
//
#import "AppDelegate.h"
#import "GCDAsyncSocket.h"
@interface AppDelegate () <GCDAsyncSocketDelegate>
@property (nonatomic,strong) GCDAsyncSocket *socket;
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    _socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
    NSError *err = nil;
    [_socket connectToHost:@"127.0.0.1" onPort:5247 error:&err ];
    if (err){
        NSLog(@"%@",err);
    }
    NSString *str = @"r";
    NSData *data =[str dataUsingEncoding:NSUTF8StringEncoding];
    [_socket writeData:data  withTimeout:-1 tag:101];//didWriteDataWithTag代理方法被触发
    return YES;
    
}
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port
{
    NSLog(@"连接成功");
    
    
}
//写数据回调的代理方法
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    //接收数据需要手动调用这个方法,didReadData代理才回调用,以下是GCDAsyncSocket.m源码中的调用顺序。
    /*
     0)[_socket readDataWithTimeout:-1 tag:109];
     1)- (void)readDataWithTimeout:(NSTimeInterval)timeout tag:(long)tag 》- (void)readDataToData:(NSData *)data
     withTimeout:(NSTimeInterval)timeout
     buffer:(NSMutableData *)buffer
     bufferOffset:(NSUInteger)offset
     maxLength:(NSUInteger)maxLength
     tag:(long)tag
     
     2)maybeDequeueRead
     3)doReadData
     4)completeCurrentRead
     5)delegate 调用-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
     */
    
    [_socket readDataWithTimeout:-1 tag:109];
    NSLog(@"%ld",tag);
    //打印的tag是101
}
//接收数据回调的代理方法
-(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
  NSLog(@"返回数据");
    NSString *str = [[NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@",str);
    NSLog(@"%ld",tag);
    //打印的tag是109
    //所以通过tag可以辨认是哪个操作,是写操作还是读操作。还是登录操作,还是注册操作,吧啦啦啦
    
}
@end

你可能感兴趣的:(GCDAsyncSocket的使用)