// // ViewController.m // socket_test // // Created by wup on 15/7/13. // Copyright (c) 2015年 wup. All rights reserved. // #import "ViewController.h" #import "AsyncSocket.h" @interface ViewController () <UITextFieldDelegate> @property (nonatomic,strong) AsyncSocket *Msocket; @property (nonatomic,assign) UInt16 socketPort; @property (nonatomic,copy) NSString *socketHost; @property (nonatomic,strong ) UITextField *txtField; @end @implementation ViewController -(AsyncSocket *)Msocket { if (!_Msocket) { _Msocket = [[AsyncSocket alloc] initWithDelegate:self]; [_Msocket connectToHost:_socketHost onPort:_socketPort withTimeout:-1 error:nil]; } return _Msocket; } -(UITextField *)txtField { if (!_txtField) { _txtField = [[UITextField alloc] initWithFrame:CGRectMake(0, 44, self.view.frame.size.width, 44)]; _txtField.backgroundColor = [UIColor greenColor]; } return _txtField; } - (void)viewDidLoad { [super viewDidLoad]; [self.view addSubview:self.txtField]; self.txtField.delegate = self; self.view.backgroundColor = [UIColor redColor]; self.socketHost = @"127.0.0.1"; self.socketPort = 50000; [self.Msocket readDataWithTimeout:-1 tag:2]; } -(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.Msocket writeData:msgdata withTimeout:-1 tag:11]; self.txtField.text = @""; } -(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port { NSLog(@" connect success!"); } -(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag { NSLog(@"%@",[NSThread currentThread]); NSString *readstr = [[NSString alloc ] initWithData:data encoding:NSUTF8StringEncoding]; if ([readstr isEqualToString:@"Are you still there?\r\n"]) { NSLog(@"send online command!"); [self sendmsg:@"online"]; } NSLog(@"%@",readstr); [self.Msocket readDataWithTimeout:30 tag:3]; } -(void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag { NSLog(@"send msg tag is :%ld and sock %@",tag,sock); } -(void)onSocketDidDisconnect:(AsyncSocket *)sock { NSLog(@"socket is disconnect!"); } -(void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket { NSLog(@"%@",newSocket); } -(void)onSocket:(AsyncSocket *)sock didReadPartialDataOfLength:(CFIndex)partialLength tag:(long)tag { } -(BOOL)onSocketWillConnect:(AsyncSocket *)sock { NSLog(@"%@",sock); return YES; } @end