iOS Gcdasyncsocket use of third-party libraries

Source: Internet
Author: User

The socket describes an IP, port pair. It simplifies the programmer's operation, knowing that the other's IP and port can send messages to each other, and the server side handles the messages sent. Therefore, the socket must contain the communication of the two, that is, the client and the service side (server).

1) The service side uses the socket listening port;

2) The client initiates the connection;

3) The service side Returns information, establishes the connection, starts the communication;

4) client, service end disconnected.


1 socket (socket) concept

Socket (socket) is the cornerstone of communication and is the basic operating unit of network communication supporting TCP/IP protocol.

When the application layer communicates data through the transport layer, TCP encounters a problem that provides concurrent services for multiple application processes at the same time. Multiple TCP connections or multiple application processes may require data to be transmitted over the same TCP protocol port. To differentiate between different application processes and connections , many computer operating systems provide a socket (socket) interface for applications interacting with the TCP/IP protocol. The application layer can communicate with the transport layer through the socket interface, differentiate the communication from different application processes or network connections, and realize the concurrent service of data transmission.

2 Establishing a socket connection

Establishing a socket connection requires at least one pair of sockets, one running on the client, called Clientsocket, and the other running on the server side, called ServerSocket.

The connection between sockets is divided into three steps: Server listening, client request, connection acknowledgement.

Server monitoring: Server-side sockets do not locate specific client sockets, but are waiting for the status of the connection, real-time monitoring network status, waiting for the client connection request.

Client request: Refers to the client's socket to make a connection request, to connect to the target is the server-side socket. To do this, the client's socket must first describe the socket of the server it is connecting to, indicate the address and port number of the server-side socket, and then make a connection request to the server-side socket.

Connection confirmation: When a server-side socket hears or receives a connection request from a client socket, it responds to a client socket request, establishes a new thread, sends a description of the server-side socket to the client, and once the client confirms the description, the two sides formally establish the connection. While the server-side socket continues to be in the listening state, it continues to receive connection requests from other client sockets.

4. Socket connection and TCP connection

When you create a socket connection, you can specify the transport layer protocol used, which can support different transport layer protocols (TCP or UDP), which is a TCP connection when a connection is made using the TCP protocol.

5. Socket connection and HTTP connection

Since the socket connection is usually a TCP connection, once the socket connection is established, the communication parties can start sending data content to each other until the two sides are disconnected. However, in real network applications, the client-to-server communication often needs to traverse multiple intermediary nodes, such as routers, gateways, firewalls, and so on, most firewalls will turn off long inactive connections and cause the Socket connection to be disconnected, so it needs to be polled to tell the network that the connection is active.

The HTTP connection uses a "request-response" approach, not only to establish a connection at the time of the request, but also to be able to reply to the server after the client has made a request to the server.

In many cases, the server side is required to proactively push the client


The standard recommended for the iphone is Cfnetwork C library programming. But programming is rather irritable. In other OSes, the processing of the socket function is often encapsulated with classes. For example, MFC's Casysncsocket. The iphone also has a similar open source project. Cocoa Asyncsocket Library, official website: http://code.google.com/p/cocoaasyncsocket/It is used to simplify The Cfnetwork call.

I. Introduction of the Asyncsocket library in the project

1. Download Asyncsocket Library Source code

2. Add the Asyncsocket Library source to the project: Just add four files in AsyncSocket.h, ASYNCSOCKET.M, AsyncUdpSocket.h and ASYNCUDPSOCKET.M in the Runloop directory.

3. Increased Cfnetwork framework in the project

In the framework directory right-click, select Add-->existing Files ..., select Cfnetwork.framework

Two. TCP Client

1. Define the Asyncsocket object in the controller header file

#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. Use Connecttohost to connect servers where needed

Where the initwithdelegate parameter in self is required. The function of each socket response in this object pointer is called by Asyncsocket.

Asyncsocket = [[Asyncsocket alloc] initwithdelegate:self];

Nserror *err = nil;

if (![ Asyncsocket connecttohost:host On:port Error:&err])

{

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

}

3. Increase the socket response event

Because Initwithdelegate will pass the current object in, so long as the current object method to implement the corresponding method.

4. About NSData Objects

The NSData object is used regardless of whether the socket is sent or received. It is defined as http://developer.apple.com/library/mac/#documentation/cocoa/reference/foundation/ Classes/nsdata_class/reference/reference.html

The NSData is primarily a data space and length with a (ID) that is pointed to.

NSString Convert to NSData object

nsdata* xmlData = [@ "testdata" datausingencoding:nsutf8stringencoding];

NSData Convert to NSString object

NSData * data;

NSString *result = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];

4. Send data

Asyncsocket WriteData method to send data, it has the following definition

-(void) WriteData: (NSData *) data withtimeout: (nstimeinterval) timeout tag: (long) tag;

The following is an instance statement.

nsdata* adata= [@ "test data" datausingencoding:nsutf8stringencoding];

[Sock Writedata:adata Withtimeout:-1 Tag:1];

In the Onsocket overload function, as defined by the send data that is specifically used to handle the socket:

-(void) onsocket (Asyncsocket *) sock Didwritedatawithtag: (long) tag

{

NSLog (@ "thread (%), onsocket:%p didwritedatawithtag:%d", [[Nsthread CurrentThread] name],

Sock,tag);

}

5. Receive the socket data.

In the Onsocket overload function, as defined by the receive data that is specifically used to handle the socket.

-(void) Onsocket: (Asyncsocket *) sock didreaddata: (NSData *) data withtag: (long) tag

In the middle, it is converted to NSString for display.

nsstring* aStr = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];

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

[ASTR release];

Asyncsocket的例子
Here's an example of using Open Source Library Asyncsocket://SocketDemoViewController.hSocketdemo//Created by Xiang Xiva on 10-7-10.Copyright __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@interfaceSocketdemoviewcontroller:Uiviewcontroller {Uitextfield *inputmsg;UILabel *outputmsg; Asyncsocket *client;}@property (Nonatomic, retain) Asyncsocket *client;@property (Nonatomic, retain)Iboutlet Uitextfield *inputmsg;@property (Nonatomic, retain)IboutletUILabel *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.mSocketdemo//Created by Xiang Xiva on 10-7-10.Copyright __mycompanyname__. All rights reserved.//#import"SocketDemoViewController.h"@implementationSocketdemoviewcontroller@synthesize inputmsg, outputmsg;@synthesize client;/*//the designated initializer. Override to perform setup, required before the view is loaded.-(ID) initwithnibname: (NSString *) Nibnameornil Bundle :(NSBundle *) Nibbundleornil {self = [super Initwithnibname:nibnameornil Bundle:nibbundleornil], if (self) {//Custom INI Tialization} return self;} *//*//Implement Loadview to create a view hierarchy programmatically, without using a nib.-(void) Loadview {}*/Implement Viewdidload to does additional setup after loading the view, typically from a nib.-(void) Viewdidload {[Super Viewdidload]; [Self connectserver:host_ip port:host_port];Listen for Read}Override to allow orientations other than the default portrait orientation.-(BOOL) Shouldautorotatetointerfaceorientation: (uiinterfaceorientation) interfaceorientation {ReturnYES;} - (void) Didreceivememorywarning {Releases the view if it doesn ' t has a superview. [Super didreceivememorywarning];Release any cached data, images, etc-aren ' t in use.} - (void) Viewdidunload {Self. Client =NilRelease 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 =Nil192.168.110.128if (![ 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"];BreakCase srv_connected: [Self ShowMessage:@ "It ' s Connected,don ' t agian"];BreakDefaultBreak }}- (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];Continue listening for read[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:-< span class= "Hljs-number" >1 tag:0];}  #pragma mark dealloc-(void) dealloc {[Client release]; [Inputmsg release]; [Outputmsg release]; [super Dealloc];}  @end             

iOS Gcdasyncsocket use of third-party libraries

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.