Original article, welcome reprint, Reprint please specify: article from [Cold River solitary Ye Shi cocos2d-x Tour Series]
Blog Address: http://blog.csdn.net/qq446569365
What it does to monitor iOS network state switching (WiFi and mobile cellular networks)
In the socket network game, Bsdsocket is often used. When the user switches the network state, the socket link disconnects, and if the return value of the receive is passed to determine if the network is disconnected, it will take a long time to wait (4-20s)
This time you need to listen to the iOS network status switch, when the user switched network status, the direct re-connect socket.
How to use in Cocos
First import NetworkInfo.h and networkinfo.m into the project
Networkinfo's GitHub Address
Then modify the appcontroller.mm file
First, refer to the two files you just imported #import "NetworkInfo.h"
Next - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions , add the following code to the function (register for monitoring)
The code is as follows
//开启网络状况的监听 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];NetworkInfo* hostReach = [NetworkInfo reachabilityWithHostName:@"www.baidu.com"] ;//网址可以修改一个连接速度较快的[hostReach startNotifier]; //开始监听,会启动一个run loop
And a callback method that joins the network state switch in the file
The code is as follows
//网络链接改变时会调用的方法 -(void)reachabilityChanged:(NSNotification *)note{ NetworkInfo *currReach = [note object]; NSParameterAssert([currReach isKindOfClass:[NetworkInfo class]]); //TODO:重连网络}
Finally, add the library file to the project:SystemConfiguration.framework
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[The Cocos2d-x journey of the lone Ye Shi in the Cold River _34] Odsocket (Bsdsocket) How to automatically re-connect when switching network state