// // ViewController.m // GCDAsyncSocket_test // // Created by wup on 15/7/13. // Copyright (c) 2015年 wup. All rights reserved. // #import "ViewController.h" #import "GCDAsyncSocket.h" @interface ViewController () <GCDAsyncSocketDelegate,UITextFieldDelegate> @property (nonatomic,strong) GCDAsyncSocket *socket; @property (nonatomic,strong) UITextField *txf; @property (nonatomic,strong) NSTimer *timer; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // dispatch_queue_t myqueue = dispatch_queue_create("com.nash.myqueue", NULL); dispatch_queue_t myqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); _txf = [[UITextField alloc] initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, 44)]; self.view.backgroundColor = [UIColor redColor]; _txf.backgroundColor = [UIColor greenColor]; [self.view addSubview:_txf]; _txf.delegate = self; _socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:myqueue]; [_socket connectToHost:@"127.0.0.1" onPort:50000 withTimeout:-1 error:nil]; [self.socket readDataWithTimeout:-1 tag:10]; _timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(keeplive) userInfo:nil repeats:YES]; // [_timer fire]; } -(void)keeplive { [self.socket writeData:[@"longconect\r\n" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:-1 tag:100]; } -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.timer invalidate]; [self.socket disconnect]; } -(BOOL)textFieldShouldReturn:(UITextField *)textField { [self sendmsg:textField.text]; return YES; } -(void)sendmsg:(NSString *)text { NSString *msgstr = [text stringByAppendingString:@"\r\n"]; NSData *msgdata = [msgstr dataUsingEncoding:NSUTF8StringEncoding]; self.txf.text = @""; [self.socket writeData:msgdata withTimeout:-1 tag:98]; } -(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag { NSLog(@"%@",sock ); } -(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port { NSLog(@"%@",[NSThread currentThread]); } -(void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { NSString *msgstr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@",msgstr); [self.socket readDataWithTimeout:30 tag:99]; NSLog(@"%@",[NSThread currentThread]); } -(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err { NSLog(@"disconnect !!! %@",err); } -(void)dealloc { [_timer invalidate]; NSLog(@"%s",__func__); } @end