IOS network programming mode Summary

Source: Internet
Author: User

IOS network programming mode Summary

IOS can use three types of api interfaces for network programming. The socket, stream, and url modes are used according to the abstract hierarchy.

I. socket mode

The socket network programming interface provided by IOS is CFSocket. CFSocket is the abstraction and encapsulation of BSD sockets. CFSocket provides almost all BSD sockets functions and is integrated with run loop to implement multi-threaded network programming and network event listening. CFSocket-based socket programming supports various types, including stream-based sockets (such as tcp) and packet-based sockets (such as udp ). Note that when necessary, the CFSocket interface in iOS does not automatically activate the cellular modem or on-demand VPN of the device.

CFSocket includes the following programming interfaces, including Socket creation and configuration, and remote communication based on the created and configured Socket.

1 Socket Creation

1. CFSocketCreate

Create a CFSocket object of a specific protocol and type

1.2. CFSocketCreateWithSocketSignature

This interface creates a CFSocket object based on a CFSocketSignature structure containing communication protocols and addresses.


1.3. CFSocketCreateConnectedToSocketSignature

This interface creates a CFSocket object and connects to a remote host.


1.4. CFSocketCreateWithNative

This interface encapsulates an existing BSD socket to create a CFSocket object.


2 Socket Configuration

2.1 CFSocketCopyAddress

Function: returns the local address of a CFSocket object.

Syntax:

SWIFT

Func CFSocketCopyAddress (_ s: CFSocket !) -> CFData!

2.2. CFSocketCopyPeerAddress

Function: return the remote address connected to a CFSocket object.

Syntax:

SWIFT

Func CFSocketCopyPeerAddress (_ s: CFSocket !) -> CFData!

2.3 CFSocketDisableCallBacks

Function: temporarily cancel a certain type of Event Callback specified when a CFSocket object is created.

Syntax:

SWIFT

Func CFSocketDisableCallBacks (_ s: CFSocket !,

_ CallBackTypes: CFOptionFlags)

2.4 CFSocketEnableCallBacks

Function: Re-allow a type of Event Callback canceled by the previously CFSocketDisableCallBacks function.

Syntax:

SWIFT

Func CFSocketEnableCallBacks (_ s: CFSocket !,

_ CallBackTypes: CFOptionFlags)

2.5 CFSocketGetContext

Function: returns the context information of a CFSocket object.

Syntax:

SWIFT

Func CFSocketGetContext (_ s: CFSocket !,

_ Context: UnsafeMutablePointer )

2.6 CFSocketGetNative

Returns the local BSD socket associated with a CFSocket object.

Syntax:

SWIFT

Func CFSocketGetNative (_ s: CFSocket !) -> CFSocketNativeHandle

2.7 CFSocketGetSocketFlags

Function: returns a flag that controls the behavior of a CFSocket object.

Syntax:

SWIFT

Func CFSocketGetSocketFlags (_ s: CFSocket !) -> CFOptionFlags


2.8 CFSocketSetSocketFlags

Function: sets a flag for controlling the behavior of a CFSocket object.

Syntax:

SWIFT

Func CFSocketSetSocketFlags (_ s: CFSocket !,

_ Flags: CFOptionFlags)

2.9 CFSocketSetAddress

Syntax:

SWIFT

Func CFSocketSetAddress (_ s: CFSocket !,

_ Address: CFData !) -> CFSocketError

Function: bind a local address to a CFSocket object and configure the socket to be in the listening state when the local socket is supported. This function corresponds to the bind and listen functions of the local socket. Once a CFSocket object is bound to an address, it depends on the socket protocol. Other processes and hosts can connect to the CFSocket object.


3. Use of Sockets

3.1 CFSocketConnectToAddress

Function: Enable a connection to a remote socket.

Syntax:

SWIFT

Func CFSocketConnectToAddress (_ s: CFSocket !,

_ Address: CFData !,

_ Timeout: CFTimeInterval)-> CFSocketError

3.2 CFSocketCreateRunLoopSource

Syntax:

SWIFT

Func CFSocketCreateRunLoopSource (_ allocator: CFAllocator !,

_ S: CFSocket !,

_ Order: CFIndex)-> CFRunLoopSource!

Function: Creates a CFRunLoopSource object for a CFSocket object. The created CFRunLoopSource object is not automatically added to a run loop. To add the run loop source to a run loop, call the CFRunLoopAddSource function of the CFRunLoop object to add the run loop source to the CFRunLoop object.

3.3 CFSocketGetTypeID

Function: return the type identifier corresponding to the opaque type of the CFSocket object.

Syntax:

SWIFT

Func CFSocketGetTypeID ()-> CFTypeID

3.4 CFSocketInvalidate

Function: disables a CFSocket object to stop receiving and sending any messages.

Syntax:

SWIFT

Func CFSocketInvalidate (_ s: CFSocket !)

3.5 CFSocketIsValid

Function: returns a Boolean value indicating whether a CFSocket object is valid and whether it can send or receive messages.

Syntax:

SWIFT

Func CFSocketIsValid (_ s: CFSocket !) -> Boolean

3.6 CFSocketSendData

Function: This function is used to send data through a CFSocket object.

Syntax:

SWIFT

Func CFSocketSendData (_ s: CFSocket !,

_ Address: CFData !,

_ Data: CFData !,

_ Timeout: CFTimeInterval)-> CFSocketError


Ii. stream programming mode

Stream programming mode provides a mode similar to unix file operations. First, create and set the stream, then open the stream, and then read and write the stream. When the stream exists, you can also query the relevant attributes of the stream to read the information about the stream, and close the stream after the stream is used.

IOS provides two types of APIS for stream programming. One is the CFStream api (including CFStream, CFReadStream, and CFWriteStream) implemented in C language at the Core Foundation framework layer ), the first type is the NSStream API (including NSStream and NSInputStream NSOutputStream) implemented in Objective-C language on the Foundation framework layer. The two provide similar interfaces and actions, some objects are of the toll-free bridged type, such as CFStream and NSStream, CFReadStream and NSInputStream, CFWriteStream and NSOutputStream. Therefore, they can be used together.

Developers can choose to use it based on their preferred language.

CFStream API interfaces:

1. CFStream Creation Interface

1.1 CFStreamCreatePairWithPeerSocketSignature

Function: Creates a pair of readable and writable streams to one socket.

1.2 CFStreamCreatePairWithSocketToHost

Function: Creates a pair of read/write streams that connect to a specific port of a specific host.

1.3 CFStreamCreatePairWithSocket

Function: Creates a pair of read/write streams connected to a socket.

1.4 CFStreamCreateBoundPair

Function: Creates a read/write stream.

Other interfaces for creating read/write streams:

1.5 CFReadStreamCreateForHTTPRequest

Function: Creates a readable stream for a CFHTTP request.

1.6 CFReadStreamCreateForStreamedHTTPRequest

Function: Creates a readable stream for a CFHTTP request whose body is kept in memory.

1.7 CFReadStreamCreateWithFTPURL

Function: creates an FTP readable stream.

1.8 CFWriteStreamCreateWithFTPURL

Function: creates an FTP readable stream.

2. CFReadStream Interface

2.1 enable and disable a stream

CFReadStreamOpen

CFReadStreamClose

2.2 read data

CFReadStreamRead

2.3. Schedule a readable stream

CFReadStreamScheduleWithRunLoop (_:_:_:)

CFReadStreamUnscheduleFromRunLoop (_:_:_:)

2.4 check the attributes of a readable stream

CFReadStreamCopyProperty (_:_:)

CFReadStreamGetBuffer (_:_:_:)

CFReadStreamCopyError (_:)

CFReadStreamGetError (_:)

CFReadStreamGetStatus (_:)

CFReadStreamHasBytesAvailable (_:)

2.5 set the attributes of a readable stream

CFReadStreamSetClient (_:_:_:_:)

CFReadStreamSetProperty (_:_:_:)

2.6 obtain the Type ID of CFReadStream

CFReadStreamGetTypeID ()

3. CFWriteStream related interfaces

3.1 CFWriteStreamClose (_:)

3.2 CFWriteStreamOpen (_:)

3.3 CFWriteStreamWrite (_:_:_:)

3.4 CFWriteStreamScheduleWithRunLoop (_:_:_:)

3.5 CFWriteStreamUnscheduleFromRunLoop (_:_:_:)

3.6 CFWriteStreamCanAcceptBytes (_:)

3.7 CFWriteStreamCopyProperty (_:_:)

3.8 CFWriteStreamCopyError (_:)

3.9 CFWriteStreamGetError (_:)

3.10 CFWriteStreamGetStatus (_:)

3.11 CFWriteStreamSetClient (_:_:_:_:)

3.12 CFWriteStreamSetProperty (_:_:_:)

3.13 CFWriteStreamGetTypeID ()

CFStream API usage steps:

1) Use the stream creation interface to create related streams;

2) Call CFReadStreamSetClient (readable stream) or CFWriteStreamSetClient (writable stream) to register the events related to the stream to be received;

3) Call CFReadStreamScheduleWithRunLoop (readable stream) or CFWriteStreamScheduleWithRunLoop (writable stream) to schedule the stream on a run loop to receive relevant events;

4) Call CFReadStreamOpen or CFWriteStreamOpen to open the created stream;

5) in the callback that is registered when the read stream is created, data is read when the kCFStreamEventHasBytesAvailable event is received. In the registered callback of the writable stream, start to send data or requests when receiving the kCFStreamEventCanAcceptBytes event;

6) after data transmission is completed, close and release the stream that is enabled and created;

2. Use of NSStream API

In ios, because the NSStream class does not support connection to a remote host, while CFStream does, to use NSStream, you need to use the stream creation function CFStreamCreatePairWithSocketToHost or CFStreamCreatePairWithSocketToCFHost to open a socket connected to the remote host and allocate a CFStream object (CFReadStream and CFWriteStream ), and cast these objects to NSStream objects (corresponding to NSInputStream and NSOutputStream ). In this way, you can use NSStream-related interfaces for network programming. For example, set the proxy object for receiving network events, schedule it to the current run loop, and open them for corresponding processing.

The code snippet is as follows:

{        NSURL *website = [NSURL URLWithString:urlStr];        if (!website) {            NSLog(@"%@ is not a valid URL");            return;        }        CFReadStreamRef readStream;        CFWriteStreamRef writeStream;        CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)[website host], 80, &readStream, &writeStream);        NSInputStream *inputStream = (__bridge_transfer NSInputStream *)readStream;        NSOutputStream *outputStream = (__bridge_transfer NSOutputStream *)writeStream;        [inputStream setDelegate:self];        [outputStream setDelegate:self];        [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];        [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];        [inputStream open];        [outputStream open];        /* Store a reference to the input and output streams so that           they don't go away.... */        ...}

When the NSStream object is opened, when the relevant stream-event network message is received, the handleEvent: function in the proxy object is called to process the network message related to the stream, such as sending requests or receiving responses to related protocols. HandleEvent: the code snippet of the function for event processing:

- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {    NSLog(@"stream:handleEvent: is invoked...");     switch(eventCode) {        case NSStreamEventHasSpaceAvailable:        {            if (stream == oStream) {                NSString * str = [NSString stringWithFormat:                    @"GET / HTTP/1.0\r\n\r\n"];                const uint8_t * rawstring =                    (const uint8_t *)[str UTF8String];                [oStream write:rawstring maxLength:strlen(rawstring)];                [oStream close];            }            break;        }        // continued ...    }}

Iii. url programming mode

The url programming mode implements network programming through URL. Any network resources (including LAN and WAN) to be accessed can be expressed and accessed using a URL, and supports resource sharing between devices. The url programming mode system supports five protocols, including http, https, file, ftp, and data, and allows users to develop and register their own classes to support additional application layer network protocols for protocol extension.

In the url programming mode, two programming interfaces can be used in IOS: NSURLSession and NSURLConnection.

We recommend that you use the NSURLSession API for the latest systems after iOS 7. For earlier versions, because NSURLSession is not supported, you must use the NSURLConnection API.

The NSURLSession programming mode completes connection requests through a session. The application creates a series of sessions for network communication. Each session coordinates a set of data transmission tasks. In each session, the application adds a series of tasks, each of which represents a specific URL request.

Compared with NSURLConnection, NSURLSession allows you to continue downloading data in the background when an application is suspended, stopped, or crashed, that is, you can cancel, restart (resume), or suspend a task, and the ability to resume downloads from pending, canceled, or failed downloads.

For simple requests, a simple NSURL object can also be used to send requests, and a NSData memory object or a file is used to extract the content pointed to by the NSURL. The NSURLConnection API can only construct an NSURLRequest object or its subclass to send a URL request to download or upload URL data. An NSURLRequest object can be used to encapsulate a URL request. For example, an HTTP method can encapsulate certain attributes of the protocol and define the usage policies of any local cached data.

The response to the NSURLRequest object consists of two parts: metadata describing the content and content data. Both APIs are encapsulated by the NSURLResponse class for metadata received using NSURLRequest requests, including the MIME type, content length, encoding, and response URL. The NSURLResponse protocol-specific subclasses can also provide additional metadata, such as NSHTTPURLResponse, which provides information such as the protocol header and the status code returned by the WEB server.

NSURLSession API usage:

The NSURLSession class supports three types of sessions (default session type, temporary session, background session) and three types of tasks (data task, download task, and upload task ).

Data tasks use NSData objects to send and receive memory data, and do not store data to a single file. Therefore, backend sessions are not supported.

The download task extracts data in the form of a file and supports background download when the application is not running.

The upload task is used to upload data (Files). It also supports background upload when the application is not running.

The difference between the default session and the background session is that the background session uses a separate process to process all data transmission tasks with some restrictions: the background session must use a specific application proxy to submit events, only HTTP and HTTPS protocols are supported. Other custom protocols are not supported. Only upload and download tasks are supported. Data tasks are not supported.

Temporary sessions do not store any data to disks. All received content is stored in the RAM associated with the session. When the session is invalid, the content received in RAM is automatically cleared.

Procedure for using the NSURLSession API:

1. Create an NSURLSessionConfiguration configuration object

The NSURLSessionConfiguration object provides a wide range of configuration options, including:

1) Private Data Storage specific to a single session, including caches, cookies, credentials, and protocols;

2) Authentication associated with a specific request or session;

3) the maximum number of connections to a host;

4) Time-out associated with a resource;

5) supports the minimum and maximum TLS versions;

6) Customized agent dictionary;

7) cookie policy control;

8) HTTP pipelining Behavior Control

2. Create an NSURLSession according to the configuration;

The following code snippet shows how to create different types of NSURLSession Objects Based on Different configuration objects.

/* Create a session for each configurations. */    self.defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];    self.backgroundSession = [NSURLSession sessionWithConfiguration: backgroundConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];    self.ephemeralSession = [NSURLSession sessionWithConfiguration: ephemeralConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

The NSURLSession API uses a proxy to Implement Asynchronous URL content access. A proxy can be a system-provided proxy or a specific proxy object provided by an application. The methods of these proxy objects are called when the task object receives data from the server or the transmission is complete.

Specify the corresponding proxy object when creating a session.

3. Add a task for a session;

Use the following method to add a data task to a session.

DataTaskWithURL (_:)

DataTaskWithURL (_: completionHandler :)

DataTaskWithRequest (_:)

DataTaskWithRequest (_: completionHandler :)

Use the following method to add a download task to a session.

DownloadTaskWithURL (_:)

DownloadTaskWithURL (_: completionHandler :)

DownloadTaskWithRequest (_:)

DownloadTaskWithRequest (_: completionHandler :)

DownloadTaskWithResumeData (_:)

DownloadTaskWithResumeData (_: completionHandler :)


Use the following method to add an upload task to a session:

UploadTaskWithRequest (_: fromData :)

UploadTaskWithRequest (_: fromData: completionHandler :)

UploadTaskWithRequest (_: fromFile :)

UploadTaskWithRequest (_: fromFile: completionHandler :)

UploadTaskWithStreamedRequest (_:)

The following is a code snippet for creating a data task:

    NSURL *url = [NSURL URLWithString: @"http://www.example.com/"];    NSURLSessionDataTask *dataTask = [self.defaultSession dataTaskWithURL: url];    [dataTask resume];

The following is a code snippet for downloading task creation:

    NSURL *url = [NSURL URLWithString: @"https://developer.apple.com/library/ios/documentation/Cocoa/Reference/"                  "Foundation/ObjC_classic/FoundationObjC.pdf"];    NSURLSessionDownloadTask *downloadTask = [self.backgroundSession downloadTaskWithURL: url];    [downloadTask resume];

4. Use the proxy method to receive data and status information


When a data task of a session receives data using a specific application proxy, the following two proxy methods must be implemented:

URLSession: dataTask: didReceiveData:

One piece of request data is provided to the session task.

URLSession: task: didCompleteWithError:

Indicates that all request data has been received.


The download task of a session should implement the following proxy methods when downloading files:

URLSession: downloadTask: didFinishDownloadingToURL:

The downloaded content is stored in a temporary file specified by a URL. Before returning this method, you must move the content of the temporary file to a permanent location and delete the temporary file.

URLSession: downloadTask: didWriteData: totalBytesWritten: totalBytesExpectedToWrite:

Provide the application with status information about the current download progress

URLSession: downloadTask: didResumeAtOffset: expectedTotalBytes:

Indicates that the application has been recovered from the previous failed download.

URLSession: task: didCompleteWithError:

Indicates that the application download has failed.


Recovery from download failure:

When the application uses the cancelByProducingResumeData: Method to cancel a download task, you can use downloadTaskWithResumeData: Or downloadTaskWithResumeData: completionHandler: Method to recreate a new download task and send resume: The generated recovery data to continue.

When the transfer fails, if the task can be recovered, call URLSession: task: didCompleteWithError: method. You can use downloadTaskWithResumeData: Or downloadTaskWithResumeData: completionHandler: method to recreate a new download task and resume data download.


The system proxy only supports basic URL resource access tasks, does not support authentication and background download, and must provide a completion handler block to submit the returned URL data to the application. The following is an example of code using a system Proxy:

     NSURLSession *delegateFreeSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];    [[delegateFreeSession dataTaskWithURL: [NSURL URLWithString: @"http://www.example.com/"]                       completionHandler:^(NSData *data, NSURLResponse *response,                                           NSError *error) {                           NSLog(@"Got response %@ with error %@.\n", response, error);                           NSLog(@"DATA:\n%@\nEND DATA\n",                                 [[NSString alloc] initWithData: data                                         encoding: NSUTF8StringEncoding]);                       }] resume];

The following describes how to create a task for a session upload task and how to create a proxy:

The session upload task uses the http post method to upload data. You can use an NSData object, a file, or a stream to provide content for the http post Request body.

When the NSData object provides the upload data, the application calls uploadTaskWithRequest: fromData: Or uploadTaskWithRequest: fromData: completionHandler: method to create the upload task.

When uploading data is provided as a file, the application calls uploadTaskWithRequest: fromFile: Or uploadTaskWithRequest: fromFile: completionHandler: method to create an upload task.

When data is being uploaded in stream mode, the application calls uploadTaskWithStreamedRequest: method to create an upload task.

The specific application proxy can obtain the upload progress information by implementing URLSession: task: didSendBodyData: totalBytesSent: totalBytesExpectedToSend: method.





Related Article

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.