Ios:socket Communication

Source: Internet
Author: User

iOS Development Socket communication

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];

Ios:socket Communication

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.