AsyncSocket

来源:互联网 发布:mac截图 编辑:程序博客网 时间:2024/06/05 11:45

//下载地址 https://github.com/robbiehanson/CocoaAsyncSocket


#import "ViewController.h"

#import "GCDAsyncSocket.h"

#import "GCDAsyncUdpSocket.h"

#import "AsyncSocket.h"



@interface ViewController ()<GCDAsyncSocketDelegate>

{

    NSInputStream *inputStream;

    NSOutputStream *outputStream;

}

@property(nonatomic,strong)AsyncSocket *asyncSocket;

@end




@implementation ViewController


- (void)viewDidLoad {

    [superviewDidLoad];


    self.asyncSocket=[[AsyncSocketalloc]initWithDelegate:self];

    [selftestSocket];

}




-(void)testSocket{

    NSData* xmlData = [@"testdata"dataUsingEncoding:NSUTF8StringEncoding];

    

    if ([self.asyncSocketconnectToHost:@"此处为服务器地址"onPort:80error:nil]) {

        NSLog(@"success");

    }else{

        NSLog(@"failed");

    } 

    [self.asyncSocketwriteData:xmlData withTimeout:-1tag:1];

}



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

    [self.asyncSocketreadDataWithTimeout:-1tag:0];

    NSLog(@"%@",host);

}


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

{

    NSLog(@"Error");

}


- (void)onSocketDidDisconnect:(AsyncSocket *)sock

{

    NSLog(@"connect is failure");

    self.asyncSocket =nil;

}


- (void)onSocketDidSecure:(AsyncSocket *)sock{

    

}


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

    

    NSString* aStr = [[NSStringalloc] initWithData:dataencoding:NSUTF8StringEncoding];

    NSLog(@"Hava received datas is :%@",aStr);



    [self.asyncSocketreadDataWithTimeout:-1tag:0];

}







- (void)didReceiveMemoryWarning {

    [superdidReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}



@end

0 0
原创粉丝点击