The process of completing an unlimited background with iOS asyncsocket these days

Source: Internet
Author: User

These days with the next asyncsocket to complete the front and back of the instant communication, at that time have thought of using the message push technology to achieve, but later thought the message pushes the unreliability or forget. The use of TCP/IP to enable the background to actively send data to the foreground function.

At the beginning of the design of the background, I have to consider the large amount of data, so when the data is large, I will use the functions of subcontracting and package to implement. TCP/IP is generally not larger than 1500 bytes when transmitting data, so I divide every 512 bytes

A package. Then, when a one-time packet receives too much, there is a sticky packet problem. Because I am using JSON in the data transfer, each sub-package is enclosed by {}, so I just want to add a section on the Baotou to not repeat the basic

The split string, and then the server receives the sub-packet each time according to this string split, the first time the first row is absolutely empty string for example: @Hinagiku {"Name" = "Guijing"}, I split the result is:

"", "Guijing", so that the first line I can skip directly, each time the sub-package is taken from the second row to start. Then the background is based on the package ID number, sequence number for the group package. If the current sub-packet is not received within 5 minutes, it represents the current packet receive failure

, requiring the client or server to resend. After the problem was solved, I began to implement the heartbeat packet function, when I was thinking that every 1 minutes, the heartbeat packet, the server put a thread. Every few seconds, all of the current TCP connections

What number is the last access time, and if this time is exceeded, the current connection is disconnected.

After the implementation, I started to implement the infinite background function. Here I do not say infinite backstage there are several ways to achieve, good trouble, I use the VoIP mode. I am using the Open source class library that is downloaded from Code4app, Asyncsocket,

And the use of Gcdasyncsocket is the same. At first it was easier to implement and the client and server connections and data transfers were done quickly. Later, in the realization of the infinite backstage, there is a very strange problem: I am running in the debug state

program, the program is hidden in the background when it is indeed possible to run indefinitely, and the TCP connection is not disconnected. But when I was running in a non-debug state, the TCP connection broke down after 3 minutes. After this problem I looked for a whole day and then

The reason was found because I commented out a line of code, causing the TCP connection to be disconnected. As a matter of principle, the implementation of the infinite background has the following steps, first in the plist file required background Modes This item added the following two items (default

This item is not in the project and needs to be added manually): App play audio or streams Audio/video using airplay and app provides Voice over IP services. IOS7 is not so troublesome, you can directly click on the project file,

Tick the following two items:

Then, in ASYNCSOCKET.M, modify the following methods:

-(BOOL) Createstreamsfromnative: (cfsocketnativehandle) Native error: (Nserror *) errptr

-(BOOL) Createstreamstohost: (NSString *) hostname onPort: (UInt16) port error: (Nserror *) errptr

Copy the following code into this method

Cfreadstreamsetproperty (Thereadstream, Kcfstreampropertyshouldclosenativesocket, KCFBooleanFalse);
Cfwritestreamsetproperty (Thewritestream, Kcfstreampropertyshouldclosenativesocket, KCFBooleanFalse);
Cfreadstreamsetproperty (Thereadstream, Kcfstreamnetworkservicetype, Kcfstreamnetworkservicetypevoip);
Cfwritestreamsetproperty (Thewritestream, Kcfstreamnetworkservicetype, Kcfstreamnetworkservicetypevoip);
[(Nsinputstream *) Thereadstream Setproperty:nsstreamnetworkservicetypevoip Forkey:nsstreamnetworkservicetype]; (Here need not add I do not know, anyway Plus will not error ...) )
[(Nsoutputstream *) Thewritestream Setproperty:nsstreamnetworkservicetypevoip Forkey:nsstreamnetworkservicetype]; (Here need not add I do not know, anyway Plus will not error ...) )

The following code is then written in the Appdelegate-(void) Applicationdidenterbackground: (uiapplication *) Application This event:

-(void) Applicationdidenterbackground: (uiapplication *) application {       = [[UIApplication Sharedapplication] Setkeepalivetimeout: handler:^{            [self heartbeat];    }];     if (backgroundaccepted)    {        NSLog (@ "backgrounding accepted");}    }


[Self heartbeat] is the way I write a heartbeat packet, this code means: every 10 minutes to the server to send a heartbeat packet, to ensure that your TCP connection is normal.

Because I used to write code like this in the Applicationdidenterbackground event, the strange problem arises:

- (void) Applicationdidenterbackground: (UIApplication *) Application {BOOL backgroundaccepted= [[UIApplication sharedapplication] Setkeepalivetimeout: -handler:^{[Self backgroundhandler];    }]; if(backgroundaccepted) {NSLog (@"Backgrounding accepted"); } [self Backgroundhandler]; }-(void) Backgroundinghandler{nslog (@"# #-->backgroundinghandler"); UIApplication* App =[UIApplication sharedapplication]; Bgtask= [App beginbackgroundtaskwithexpirationhandler:^{        //[app Endbackgroundtask:bgtask];    }]; Dispatch_async (Dispatch_get_global_queue (Dispatch_queue_priority_default,0), ^{         while(1) {NSLog (@"counter:%d", count++); NSLog (@"timer:%f", [app backgroundtimeremaining]); Sleep (1); }    });}

This kind of code is in order to borrow more time in the background, but we do not need to borrow time after the use of VoIP, when the TCP supervisor hears the message, the program will wake up from hibernation for about 10 seconds, so that in this 10 seconds we have received the message processing finished on the line. This is an online tutorial written out of a misunderstanding, we use

There is absolutely no need to borrow time for VoIP.

I changed the following code to the above code, after my program hangs in the background, I still can't receive the message sent to the server. I feel my code is right, exactly where the mistake was made. After looking for a few hours, I inadvertently see a reminder: Background Listening messages must be run in the real machine, in the simulator is listening

Less than that. Then I changed the test environment to an ipad, and I got the message and found my own stupidity. Because the ipad is too troublesome, I'm using a simulator test. Hey, in the future we test this code or use the real machine it, do not like me by the pit ...

This article almost also recorded here, I am a new iOS, some of the understanding may not be correct, I hope everyone pointed out to learn together.

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.