Learning socket programming in iOS from scratch-highly concurrent multi-thread Server

Source: Internet
Author: User

Learning socket programming in iOS from scratch-highly concurrent multi-thread Server

In the previous article "I learned socket programming from the beginning in iOS -- HTTP1.0 server", we have been exposed to the HTTP server built by OC.

For the sake of user experience and robustness, this HTTP server is improved to multi-thread.
First, the AnsycSocket class is implemented based on the OC Runloop. Runloop implements asynchronous calling of methods, but does not support multithreading.
Here, we will first distinguish the differences between multi-thread and method asynchronous calls. They can all avoid thread blocking, except that multithreading is a new thread processing task, which notifies the main thread after processing is complete. Asynchronous Method calling is essentially a method calling in the main thread, however, the main thread does not block waiting for the execution result of the method, but continues to execute the original task until the method execution is complete. In a sense, socket programming does not always require the server to support multithreading, because adding a thread will also increase the CPU burden, and their execution effect is similar.
However, considering this situation, we should find that multithreading also has an essential reason: assume that the user uploads an image and requests to process it, assuming that image processing is very complex and involves a large amount of computing, If you execute the image processing method in the main thread at this time, the system's execution efficiency will be greatly reduced, and the user experience will be deteriorated. If a new thread is added, the processing advantages of the multi-core processor will be fully utilized, greatly improving the user experience.
Therefore, we do not need to add a thread for each new socket connection. We should make full use of the advantages of multi-core processors, add threads, and improve the execution speed when processing data.
Because of this, the callback function of AnsycSocket itself is asynchronous and does not support multithreading. If you call the writeData method of an AnsycSocket-class object in a child thread (write data to the socket) will not play any role. The solution is to put data processing in a new thread and execute the writeData method and UI-related changes in the main thread.
The key function to be modified is the didReadData method:

-(Void) onSocket :( AsyncSocket *) sock didReadData :( NSData *) data withTag :( long) tag {// process data}

We can simply modify this method to support multi-threaded data processing.

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{    __block AsyncSocket *localSocket = sock;    __block NSData *localData = data;    dispatch_async(dispatch_get_global_queue(0, 0), ^{        NSLog(@thread = %@,[NSThread currentThread]);        [self dealWithData:localSocket Data:localData];    });}

Here, three block types of objects are created to avoid circular references in the block.
Next we will implement the dealWithData method:

-(Void) dealWithData :( AsyncSocket *) sock Data :( NSData *) data {// This method is very similar to the didReadData method of AnsycSocket/* processing related data */dispatch_async (dispatch_get_main_queue (), ^ {[sock writeData: data withTimeout:-1 tag: ECHO_MSG]; [sock disconnectAfterWriting] ;});}

It can be seen that a thread is simply added and the content originally implemented in the didReadData method is moved to the custom function. After processing the data, remember to write the data in the main thread.

 

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.