Network and multi-task, learning httpserver

Source: Internet
Author: User

From: http://blog.csdn.net/kmyhy/article/details/7170315 #

Original article: Apple Reference Database "network and multitasking"

Multitasking is a key feature of ios4. Multi-task allows your application to run and suspend in the background. This is a good thing for the system, but it will seriously interfere with the execution of network tasks for your application. This article explains how to handle many tasks in network applications.

This article consists of the following parts:

Introduction

Basic

Listen to socket

Data socket

Advanced APIs

Implementation Details

Be careful with your dog!

Concurrency

Run Loops

Socket recycling Test

Advanced

Background task

Resume

Special roles in multiple tasks

Background execution 

VoIP sockets

Revision

Introduction

Multi-task introduction in ios4 adds complexity to network applications. When IOS puts your program in the background, the program may soon be suspended. In this case, the code in the program will not be executed again. This will cause the program to be unable to process data sent from the network. When a program is suspended, the system may recycle its socket resources and close the socket connection. Of course, IOS has made a special design for compatibility between network applications and multi-task tasks to reduce the workload of programmers, but you still need to do some necessary processing in your program. In the basic section, you will greatly improve the program's network behavior to be compatible with the current multi-task,

This article describes the basic steps for compatibility between network applications and multiple tasks ). Then, we describe the specific implementation details (Implementation Details) and show you the benefits of making full use of multitasking in network applications (advanced ).

Before that, you should be familiar with the iOS app lifecycle-seeIOS Application Programming Guide. This article uses the terms defined in this document, such as foreground, background, and suspension.

Finally, this article applies to developers who have not made their programs compatible with multiple tasks. If your program meetsIOS Application Programming GuideFor the categories mentioned in, read the section multitasking superpowers.

Basic

All IOS network APIS is implemented based on BSD socket. Therefore, two basic sockets types should be supported:

  • Listen to sockets-Receives TCP connection requests.
  • Data sockets-It is used to transmit data over the network. Data sockets usually represents a TCP connection or is used to access a UDP port.

The following describes how to handle multiple tasks for each type of sockets.

The followingsections describe how to handle multitasking for each type of socket.

Listen to socket

For multi-task listening socket, the processing is very simple: when the program enters the background, the socket should be closed; when the program returns to the foreground, re-open the socket. There are two main reasons:

  • When your application enters the background, it will be suspended. Once it is suspended, it cannot process the client connection on the listening socket. However, the kernel still regards socket as valid. If the client connects to the socket, the kernel will receive the connection, but in fact your program can no longer use it for communication. Although the client will give up, it will waste a little time. Therefore, it is better to disable socket when the program arrives at the background. Because the client connection is immediately rejected by the kernel.
  • If the system suspends your program, the resources on the listening port will be recycled later. Even if your program resumes running, it cannot be listened to again. The program may be notified or not notified, depending on how it manages the listening socket. A simple method to avoid this situation is to completely disable the listening socket when the program enters the background.

Remember, when the program closes the listening socket, it will also stop bonjour registration on the socket.

Data socket

The data socket situation is more complex, depending on what your data socket is doing. When a program enters the background, especially when it is suspended, you need to decide whether to disable the data socket or keep the data socket open. The key depends on how easy it is to close and re-open your data socket:

  • If you re-open the socket is simple, low-cost, and there is no user can detect the consequences, it is best to close the socket when the program enters the background, and then re-open it when returning to the foreground. These are all very simple. If so, you can ignore the following content.
  • If you re-open the socket is slow, expensive, or noticed, you may want to keep it open after the program enters the background. This usually occurs when the user switches from your program to another program and then quickly switches back. You do not want the user to be affected by unnecessary network latency. However, if you keep the socket open, you must do some processing, as described later.

If you want to keep the data socket open after the program enters the background, you must handle the socket error. Error handling is common, but this is especially important. After the program is suspended, the socket resources may be recycled by the kernel, so that all network operations on the socket will fail. All you can do is to close the socket.

Note: 

When your program resumes execution, the socket of the recycled resource will return an error. We did not specify what the error is, and I will explain it later. However, in many cases, this error may be unexpected. It is an ebadf! Generally, ebadf means that the program passes an invalid file descriptor to the system call. When a socket resource is recycled, it is not because the file descriptor is invalid, but the socket is unavailable.

Unfortunately, in this case, it is impossible to use another unused error code, because the error code that can be returned by system functions has been strictly limited.

If you use the data SOCKET protocol to support the suspension (sleep) mode, you should start the suspension mode when you enter the background, and disable the suspension mode when you enter the foreground. For example, the idle command supported by IMAP allows the client to send asynchronous notifications when the inbox content is updated. When your program is suspended, you cannot receive these notifications. Therefore, when the program enters the background, you must want to cancel these idle commands.

Advanced APIs

The content of socket is discussed earlier, but it is enough to use the upper-layer protocol on the socket. For example:

  • If you use nsstream to Manage TCP connections, nsstream automatically connects to cfstream (a specific subclass of cfstream cfsocketstream). cfstream manages the underlying socket.
  • If you use nsurlconnection, it is implemented using a cfstream (cfhttpstream), instead it uses another cfstream (cfsocketstream this time) to manage the underlying socket.

Assume that the data socket belongs to these high-level structures and its resources are recycled by the kernel, an error is reported for these high-level structures. You should detect and handle this error just like handling all other network errors. For example:

  • If you use nsstream, you will receive the nsstreameventhasbytesavailable event. You can perform processing when reading the stream. [nsinputstream-read: maxlength:] will return-1, indicating that an error has occurred. You can call [nsstream streamerror] to obtain accurate errors.
  • If you use nsurlconnection, the connection object will indicate this error by calling connection: didfailwitherror: Delegate method.

Implementation Details

This section describes important notes when you prepare your program to respond to multi-task switching.

Be careful with your dog!

As mentioned above, when your program is transferred from the foreground to the background, it can continue some important work, mainly in applicationdidenterbackground: Delegate method. Most importantly, these tasks should be completed quickly. If the program takes too long in applicationdidenterbackground: method, it will be killed by a dog (system process.

Note:

For more information about watchdog, see Technical Note tn2151, 'Understanding and analyzing iphoneos application crash report'AndTechnical Q & A qa1693, 'synchronous networking on themain thread'.

In this article, any operations involving network waits are "too long. That's because when the program enters the background, the network will immediately become "unresponsive ". Therefore, the program takes too long in applicationdidenterbackground: method until it finally becomes a dog's "mouth food ".

Not all network operations will wait. For example, disable socket listening in applicationdidenterbackground: method; Disable socket listening is always fast.

You can even transfer data at this time. For example, if you want to send a command to keep the connection in silent mode, this is feasible because the command is placed in the socket cache of the kernel. In this case, the sent command only copies data to the socket cache and does not take much time.

The trouble is that your program tries to send commands and waits for a response. If the network response is slow and the response is delayed, your program will be killed by the dog. When you have to wait for the network, you should use background tasks (using [uiapplicationbeginbackgroundtaskwithexpirationhandler:]). For example, use the silent command to enter the "silent" mode. Then your applicationdidenterbackground: the method should be:

  1. Start an asynchronous thread to send the quiesce command and wait for the response
  2. Start a background task and apply for additional time to complete the task
  3. Return

This gives your program extra time to execute the quiesce command instead of occupying too much time in the applicationdidenterbackground method.

Always remember that all background tasks must provide a time-out handler so that the system can call it when the background task ends immediately. Timeout handler, such as applicationdidenterbackground: The delegate method, which will be monitored by the system process watchdog. If a timeout handler takes too much time, the program will be forcibly terminated. If you can ensure that the network operation does not wait, it can be performed in the handler (applicationdidenterbackground: Method) that times out. You can directly close a data socket without notifying the remote end.

Concurrency

If you want to use the network in the program, it is very likely that you will continue to execute the background task when the program is returned to the background, even if it is a short time. When you start a background task, you must provide a time-out handler to cancel the background task. Timeout handler runs in the main thread. It must cancel background tasks before the main thread returns (because your program will be suspended or terminated soon ). As mentioned above, Handler timeout must be completed quickly because it takes too long to be forcibly terminated by watchdog.

This leads to many restrictions when designing a program. Most seriously, you cannot use the synchronization (blocking) network APIs in multiple threads. This is because multithreading is difficult to cancel, and a well-implemented timeout handler needs to support the cancellation operation.

For example, a synchronous blocking listening thread is usually blocked when receiving system calls. When the user presses the Home button and the program is placed in the background, you should close the socket. But how do you unlock the blocked threads in system calls? Obviously, there is no good way.

In addition, consider this situation. Your program needs to be downloaded in the background of big data, but the network is very slow, so long as the program has used up all the background task execution time. At this time, the system starts to run the timeout handler in the main thread, and then the program closes the connection before returning. How do you deal with the blocking thread waiting to read data? Similarly, there is no good way.

Therefore, to support multitasking, you may have to use the Asynchronous Network APIs. IOS provides a variety of similar APIs-from the underlying APIs, such as GCD to advanced APIs, such as nsurlconnection, and many middle-layer APIs-we encourage you to use them.

Run Loops

If you use a Network API-based run loop, you may need to run the runloop in a timeout handler to give the time required for the run loop to complete. In this case, you must run the run loop in the custom run loop mode. We do not support running the runloop in the default mode in the time-out handler (applicationdidenterbackground. Remember, if you use this technology, you must customize all relevant run loop sources in the default mode.

Socket recycling Test

If you want to write code to process the socket resources that will be recycled by the kernel, you should perform some tests. The system intentionally "unrecoverable ented" the details of socket resources, which may change in the future. However, in the ios4.0-4.3 system, the following actions will cause the system to recycle socket resources:

  1. Transfer the program to the background;
  2. Suspends the program;
  3. Lock screen;

When your program resumes running on the foreground, the program's sockets has been destroyed.

Advanced

If your app needs to run long-time network tasks, you can improve the user experience through two things:

  • Use background tasks for network transmission;
  • Resumable Transmission)

Background task

One of the common applications of background tasks is to avoid network interruption. If you start transferring large files and switch to other programs, the background tasks can continue in the background. If everything goes smoothly, file transmission should be completed when the user returns the program. To implement background tasks in your app, you do not need to divide the logic into two parts: "foreground" and "background. It is a good practice to start background tasks every time the program starts a time-consuming operation, even if the program runs on the foreground. When the program is in the foreground, the background task has no impact. However, when the user switches the program to the background, the background task can continue to run until the task is completed.

Resumable upload

If you want to run a background transmission task for a long time, it is vital to support resumable upload. Resumable upload is particularly useful in the following scenarios:

  • The device does not support multiple tasks;
  • Network interruption during transmission;
  • The program requests background tasks, but is rejected by the system (that is, the [uiapplication beginbackgroundtaskwithexpirationhandler:] method returns uibackgroundtaskinvalid );
  • Fewer system resources, the system must suspend and terminate the application. At this time, the background task is not completed;
  • The transfer task requires more time, And the backend task is not available enough.
  • If the transfer takes more time than the background task will allow

All of these cases can be solved by resumable data transfer. Resumable upload is very easy. For HTTP, most servers support the enitty tag and byteranges, which is the prerequisite for breakpoint download. Moreover, nsurlconnection can use these features. You can refer to the HTTP protocol specification (RFC 2616). Resumable upload requires higher skills, which also depends on the upload server. Resumable upload is not supported without modifying the server code.

It is also easy to implement FTP breakpoint download. You can specify the kcfstreampropertyftpfiletransferoffset attribute when using cfftpstream to start downloading. Cfftpstream does not support FTP breakpoint upload (R.4086998). In addition, FTP has very little security support (the user name, password, and data are transmitted in plain text). It is hard to imagine that FTP is still used for uploading on the Internet.

Special roles in multiple tasks

In a multitasking system, some apps have a special position. For example, an audio player can be played in the background without being suspended. This section describes the associations between these "special roles" and networks. The two types of special roles related to the network are:

  • Code running in the background
  • VoIP sockets

This section discusses the two.

Background execution

Some of the most common special multitasking programs can execute code in the background. For example, a music player can be played on the background without being suspended. In many documents, the word "back to the background" is a synonym for "can be suspended. This is a good rule of thumb, but this rule is not applicable to programs that can be executed in the background. For these programs, returning to the background does not mean that the program will be suspended. Only after you stop a task that does not suspend it will it become "suspended ". Taking the music player as an example, it becomes "suspended" only after it stops playing ".

Note that this is the same as the background task ("be careful with your dog !" Is different from that discussed in "advanced. Any app can execute code for subsequent tasks within a limited period of time. After the background task is completed, these programs become "suspended ".

VoIP sockets

A VoIP (IP voice) program is designed to run continuously so that it can listen to VoIP control connections. However, to minimize the usage of system memory, it is suspended when it is not activated. For this reason, the VoIP program must register a data socket for the control connection. The registered socket has two features:

  • When the program is suspended, the system will monitor the socket action of the program. If data is sent to the socket, the system restores the execution of the APP (even in the background) to read the data and take appropriate actions (for example, notifying the user of a call ).
  • Socket resources will not be recycled. Therefore, you do not need to worry about the destruction of the socket after the program is suspended.

For more information about how to create a VoIP program, seeIOS Application Programming Guide.

 

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.