你好,歡迎來到IOS教程網

 Ios教程網 >> IOS使用技巧 >> IOS技巧綜合 >> CocoaAsyncSocketDemo

CocoaAsyncSocketDemo

編輯:IOS技巧綜合
[摘要]本文是對CocoaAsyncSocketDemo的講解,對學習IOS蘋果軟件開發有所幫助,與大家分享。

工程圖:

代碼:

viewController.h

#import <UIKit/UIKit.h>
//加入頭文件
#import "AsyncSocket.h"
@interface ViewController : UIViewController<AsyncSocketDelegate>
@end

viewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    AsyncSocket *socket=[[AsyncSocket alloc] initWithDelegate:self];
    [socket connectToHost:@"www.baidu.com" onPort:80 error:nil];
    
    [socket readDataWithTimeout:3 tag:1];
    [socket writeData:[@"GET / HTTP/1.1nn" dataUsingEncoding:NSUTF8StringEncoding] withTimeout:3 tag:1];
    
}

#pragma -mark -socket代理
- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
    NSLog(@"did connect to host");
}
- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
    NSLog(@"did read data");
    NSString* message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"message is: n%@",message);
}

輸出結果:

2015-01-12 11:25:05.460 CocoaAsyncSocketDemo[2001:127210] did connect to host

2015-01-12 11:25:42.699 CocoaAsyncSocketDemo[2001:127988] Terminating since there is no system app.

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved