socket第三方庫 AsyncSocket(GCDAsyncSocket)

Socket描述了一個IP、端口對。它簡化了程序員的操做,知道對方的IP以及PORT就能夠給對方發送消息,再由服務器端來處理髮送的這些消息。因此,Socket必定包含了通訊的雙發,即客戶端(Client)與服務端(server)。 html

1)服務端利用Socket監聽端口; 程序員

2)客戶端發起鏈接; 編程

3)服務端返回信息,創建鏈接,開始通訊; 服務器

4)客戶端,服務端斷開鏈接。 網絡


1套接字(socket)概念 併發

套接字(socket)是通訊的基石,是支持TCP/IP協議的網絡通訊的基本操做單元。 app

應用層經過傳輸層進行數據通訊時,TCP會遇到同時爲多個應用程序進程提供併發服務的問題。多個TCP鏈接或多個應用程序進程可能須要經過同一個 TCP協議端口傳輸數據。爲了區別不一樣的應用程序進程和鏈接,許多計算機操做系統爲應用程序與TCP/IP協議交互提供了套接字(Socket)接口。應 用層能夠和傳輸層經過Socket接口,區分來自不一樣應用程序進程或網絡鏈接的通訊,實現數據傳輸的併發服務。 框架

2 創建socket鏈接 iphone

創建Socket鏈接至少須要一對套接字,其中一個運行於客戶端,稱爲ClientSocket,另外一個運行於服務器端,稱爲ServerSocket。 socket

套接字之間的鏈接過程分爲三個步驟:服務器監聽,客戶端請求,鏈接確認。

服務器監聽:服務器端套接字並不定位具體的客戶端套接字,而是處於等待鏈接的狀態,實時監控網絡狀態,等待客戶端的鏈接請求。

客戶端請求:指客戶端的套接字提出鏈接請求,要鏈接的目標是服務器端的套接字。爲此,客戶端的套接字必須首先描述它要鏈接的服務器的套接字,指出服務器端套接字的地址和端口號,而後就向服務器端套接字提出鏈接請求。

鏈接確認:當服務器端套接字監聽到或者說接收到客戶端套接字的鏈接請求時,就響應客戶端套接字的請求,創建一個新的線程,把服務器端套接字的描述發 給客戶端,一旦客戶端確認了此描述,雙方就正式創建鏈接。而服務器端套接字繼續處於監聽狀態,繼續接收其餘客戶端套接字的鏈接請求。

 

四、SOCKET鏈接與TCP鏈接

建立Socket鏈接時,能夠指定使用的傳輸層協議,Socket能夠支持不一樣的傳輸層協議(TCP或UDP),當使用TCP協議進行鏈接時,該Socket鏈接就是一個TCP鏈接。

 

五、Socket鏈接與HTTP鏈接

因爲一般狀況下Socket鏈接就是TCP鏈接,所以Socket鏈接一旦創建,通訊雙方便可開始相互發送數據內容,直到雙方鏈接斷開。但在實際網 絡應用中,客戶端到服務器之間的通訊每每須要穿越多箇中間節點,例如路由器、網關、防火牆等,大部分防火牆默認會關閉長時間處於非活躍狀態的鏈接而致使 Socket 鏈接斷連,所以須要經過輪詢告訴網絡,該鏈接處於活躍狀態。

而HTTP鏈接使用的是「請求—響應」的方式,不只在請求時須要先創建鏈接,並且須要客戶端向服務器發出請求後,服務器端才能回覆數據。

不少狀況下,須要服務器端主動向客戶端推送


iphone的標準推薦CFNetwork C庫編程.可是編程比較煩躁。在其它OS每每用類來封裝的對Socket函數的處理。好比MFC的CAsysncSocket.在iphone也有相似於 開源項目.cocoa AsyncSocket庫, 官方網站:http://code.google.com/p/cocoaasyncsocket/ 它用來簡化 CFnetwork的調用.

一.在項目引入ASyncSocket庫

  1.下載ASyncSocket庫源碼

  2.把ASyncSocket庫源碼加入項目:只須要增長RunLoop目錄中的AsyncSocket.h、AsyncSocket.m、AsyncUdpSocket.h和AsyncUdpSocket.m四個文件。

  3.在項目增長CFNetwork框架

       在Framework目錄右健,選擇Add-->Existing Files...    , 選擇 CFNetwork.framework

 

二.TCP客戶端

  1. 在controller頭文件定義AsyncSocket對象

#import <UIKit/UIKit.h>

#import "AsyncSocket.h"

 

@interface HelloiPhoneViewController : UIViewController {

    UITextField    * textField;

    AsyncSocket * asyncSocket;

}

@property (retain, nonatomic) IBOutlet UITextField *textField;

- (IBAction) buttonPressed: (id)sender;

- (IBAction) textFieldDoneEditing: (id)sender;    

@end

 

  2.在須要聯接地方使用connectToHost聯接服務器

  其中initWithDelegate的參數中self是必須。這個對象指針中的各個Socket響應的函數將被ASyncSocket所調用.

 

    asyncSocket = [[AsyncSocket alloc] initWithDelegate:self]; 

    NSError *err = nil; 

    if(![asyncSocket connectToHost:host on:port error:&err]) 

    { 

        NSLog(@"Error: %@", err); 

    } 

 

3.增長Socket響應事件

     由於initWithDelegate把將當前對象傳遞進去,這樣只要在當前對象方法實現相應方法.

 

4.關於NSData對象

    不管SOCKET收發都採用NSData對象.它的定義是 http://developer.apple.com/library/mac /#documentation/Cocoa/Reference/Foundation/Classes/NSData_Class/Reference/Reference.html

   NSData主要是帶一個(id)data指向的數據空間和長度 length.

    NSString 轉換成NSData 對象

 

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

 

   NSData 轉換成NSString對象

 

   NSData * data;

   NSString *result = [[NSString alloc] initWithData:data  encoding:NSUTF8StringEncoding];

 

4.發送數據

     AsyncSocket  writeData    方法來發送數據,它有以下定義

    - (void)writeData:(NSData *)data withTimeout:(NSTimeInterval)timeout tag:(long)tag;

 

如下是一個實例語句.

     NSData* aData= [@"test data" dataUsingEncoding: NSUTF8StringEncoding];

     [sock writeData:aData withTimeout:-1 tag:1];

 在onSocket重載函數,有如定義採用是專門用來處理SOCKET的發送數據的:

    -(void)onSocket(AsyncSocket *)sock didWriteDataWithTag:(long)tag

{

      NSLog(@"thread(%),onSocket:%p didWriteDataWithTag:%d",[[NSThread currentThread] name],

     sock,tag);

 

5.接收Socket數據.

    在onSocket重載函數,有如定義採用是專門用來處理SOCKET的接收數據的.

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

在中間將其轉換成NSString進行顯示.

 

    NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

    NSLog(@"===%@",aStr); 

    [aStr release];

Asyncsocket的例子
下面是用開源的庫Asyncsocket的例子:

//
//  SocketDemoViewController.h
//  SocketDemo
//
//  Created by xiang xiva on 10-7-10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "AsyncSocket.h"
#define SRV_CONNECTED 0
#define SRV_CONNECT_SUC 1
#define SRV_CONNECT_FAIL 2
#define HOST_IP @"192.168.110.1"
#define HOST_PORT 8080

@interface SocketDemoViewController : UIViewController {
 
 UITextField *inputMsg;
 UILabel *outputMsg;
 AsyncSocket *client;
}

@property (nonatomic, retain) AsyncSocket *client;
@property (nonatomic, retain) IBOutlet UITextField *inputMsg;
@property (nonatomic, retain) IBOutlet UILabel *outputMsg;

- (int) connectServer: (NSString *) hostIP port:(int) hostPort;
- (void) showMessage:(NSString *) msg;
- (IBAction) sendMsg;
- (IBAction) reConnect;
- (IBAction) textFieldDoneEditing:(id)sender;
- (IBAction) backgroundTouch:(id)sender;

@end

 

//
//  SocketDemoViewController.m
//  SocketDemo
//
//  Created by xiang xiva on 10-7-10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "SocketDemoViewController.h"

@implementation SocketDemoViewController

@synthesize inputMsg, outputMsg;
@synthesize client;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

 

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    //[super viewDidLoad];
 [self connectServer:HOST_IP port:HOST_PORT];
 //監聽讀取
 
}

 

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
 // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
 
 // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
 self.client = nil;
 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;
}

- (int) connectServer: (NSString *) hostIP port:(int) hostPort{
 
 if (client == nil) {
  client = [[AsyncSocket alloc] initWithDelegate:self];
  NSError *err = nil;
  //192.168.110.128
  if (![client connectToHost:hostIP onPort:hostPort error:&err]) {
   NSLog(@"%@ %@", [err code], [err localizedDescription]);
   
   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host "
           stringByAppendingString:hostIP]
               message:[[[NSString alloc]initWithFormat:@"%@",[err code]] stringByAppendingString:[err localizedDescription]]
                 delegate:self
              cancelButtonTitle:@"OK"
              otherButtonTitles:nil];
   [alert show];
   [alert release];
   //client = nil;
   return SRV_CONNECT_FAIL;
  } else {
   NSLog(@"Conectou!");
   return SRV_CONNECT_SUC;
  }
 }
 else {
  [client readDataWithTimeout:-1 tag:0];
  return SRV_CONNECTED;
 }
 
}

- (IBAction) reConnect{
 int stat = [self connectServer:HOST_IP port:HOST_PORT];
 switch (stat) {
  case SRV_CONNECT_SUC:
   [self showMessage:@"connect success"];
   break;
  case SRV_CONNECTED:
   [self showMessage:@"It's connected,don't agian"];
   break;
  default:
   break;
 }
}

- (IBAction) sendMsg{
 
 NSString *inputMsgStr = self.inputMsg.text;
 NSString * content = [inputMsgStr stringByAppendingString:@"\r\n"];
 NSLog(@"%a",content);
 NSData *data = [content dataUsingEncoding:NSISOLatin1StringEncoding];
 [client writeData:data withTimeout:-1 tag:0];
 
 //[data release];
 //[content release];
 //[inputMsgStr release];
 //繼續監聽讀取
 //[client readDataWithTimeout:-1 tag:0];
}

#pragma mark -
#pragma mark close Keyboard
- (IBAction) textFieldDoneEditing:(id)sender{
 [sender resignFirstResponder];
}

- (IBAction) backgroundTouch:(id)sender{
 [inputMsg resignFirstResponder];
}

#pragma mark socket uitl

- (void) showMessage:(NSString *) msg{
 UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"Alert!"
                                                    message:msg
                                                   delegate:nil
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:nil];
    [alert show];
    [alert release];
}


#pragma mark socket delegate

- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port{
 [client readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    NSLog(@"Error");
}

- (void)onSocketDidDisconnect:(AsyncSocket *)sock
{
 NSString *msg = @"Sorry this connect is failure";
 [self showMessage:msg];
 [msg release];
 client = nil;
}

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

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
 
 NSString* aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
 NSLog(@"Hava received datas is :%@",aStr);
 self.outputMsg.text = aStr;
 [aStr release];
 [client readDataWithTimeout:-1 tag:0];
}

#pragma mark dealloc

- (void)dealloc {
 
 [client release];
 [inputMsg release];
 [outputMsg release];
    [super dealloc];
}

@end
相關文章
相關標籤/搜索