首页 > 代码库 > 在appdelegate中尝试解决socket掉线问题
在appdelegate中尝试解决socket掉线问题
#import <UIKit/UIKit.h>
#import "MainViewController.h"
#import "Reachability.h"
@interface AppDelegate : UIResponder <UIApplicationDelegate,SRWebSocketDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, readwrite) SRWebSocket *warbleSocket;
@property (nonatomic, readwrite) BOOL socketReady;
@property (nonatomic) NSTimer* tickTimer;
- (void)connectChatServer;
- (void)disconnectChatServer;
- (void)sendMsg:(NSString*)strMsg;
@end
#import "AppDelegate.h"
#import "ASIHTTPRequest.h"
#import "MD5.h"
#import "ASIFormDataRequest.h"
#import "comm.h"
#import "CBContact.h"
#import "EGODatabase.h"
#import "ChatMessage.h"
#import "InfoMessage.h"
#import "CBContact.h"
#import "MessageFrame.h"
#import "MessageCell.h"
#import "ASIHTTPRequest.h"
#import "SVProgressHUD.h"
#import "MD5.h"
#import "NoticeMessage.h"
#import "MyProfileTableViewController.h"
#import "ContactDetailTableViewController.h"
#import "ChatViewController.h"
#import "InfoViewController.h"
#import "NoticeViewController.h"
#import "ContactDetailTableViewController.h"
#import "ContactDetailViewController.h"
#import "UIColor+Extensions.h"
#import "NSString+Pinyin.h"
#import "comm.h"
#import <Crashlytics/Crashlytics.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
//TODO:connect to socket.io server
//load server configuration
//load advertisement
//Enabling keyboard manager
self.socketReady = NO;
[Crashlytics startWithAPIKey:@"9d0b0e078333459a3160c13c42d1d2bfab448df5"];
return YES;
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSLog(@"deviceToken: %@", deviceToken);
NSString *strDev = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]stringByReplacingOccurrencesOfString: @">" withString: @""] stringByReplacingOccurrencesOfString: @" " withString: @""];
NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];
[defs setValue:strDev forKey:@"deviceToken"];
NSLog(@"%@",strDev);
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
NSLog(@"Error in registration. Error: %@", error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
NSLog(@" 收到推送消息 : %@",[[userInfo objectForKey:@"aps"] objectForKey:@"alert"]);
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)logoutWebServer
{
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
// [pref setValue:@"" forKey:@"pwd"];
//服务器端推出登录;
NSString *strToken = [pref stringForKey:@"logintoken"];
NSString *strUrl = [NSString stringWithFormat:@"%@/appLogout?token=%@",WEB_SERVER_HOST,strToken];
NSURL *url = [NSURL URLWithString:strUrl];
__block ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
NSLog(@"退出登录 %@",responseString);
NSError *error = nil;
NSData *jsonData = http://www.mamicode.com/[responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSString *msgCode = [dict objectForKey:@"code"];
if ([msgCode isEqualToString:@"200"]) {
NSLog(@"成功退出!");
}
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(@"退出登录失败 error is %@",error.description);
}];
[request startAsynchronous];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
// [[NSNotificationCenter defaultCenter] postNotificationName:@"AppDisconnectChatServer" object:nil];
[self disconnectChatServer];
[self logoutWebServer];
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
NSString* strUid = [pref stringForKey:@"uid"];
NSString* strPwd = [pref stringForKey:@"pwd"];
if (!strUid || !strPwd || [strUid isEqualToString:@""] || [strPwd isEqualToString:@""]) {
return;
}
else
{
[self connectChatServer];
[[NSNotificationCenter defaultCenter] postNotificationName:@"AppLogin" object:nil];
}
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
- (void)reconnectChatServer
{
NSLog(@"reconnect to chat server...");
if (self.socketReady == NO) {
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
NSString* strUid = [pref stringForKey:@"uid"];
NSString* strPwd = [pref stringForKey:@"pwd"];
if (![strUid isEqualToString:@""] && ![strPwd isEqualToString:@""]) {
self.warbleSocket = [[SRWebSocket alloc] initWithURL:[[NSURL alloc] initWithString:CHAT_SERVER_HOST]];
self.warbleSocket.delegate = self;
[self.warbleSocket open];
}
[self performSelector:@selector(reconnectChatServer) withObject:nil afterDelay:10.0];
}
}
- (void)connectChatServer
{
NSLog(@"connect to chat server...");
// if (self.socketReady == NO) {
self.warbleSocket = [[SRWebSocket alloc] initWithURL:[[NSURL alloc] initWithString:CHAT_SERVER_HOST]];
self.warbleSocket.delegate = self;
[self.warbleSocket open];
// }
}
- (void)disconnectChatServer
{
NSLog(@"disconnect from chat server...");
[self.warbleSocket close];
}
- (void)sendMsg:(NSString*)strMsg
{
[self.warbleSocket send:strMsg];
}
//WebSocket连接上服务器
- (void)webSocketDidOpen:(SRWebSocket *)webSocket
{
self.socketReady = YES;
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
NSString* strUid = [pref stringForKey:@"uid"];
NSString* strPwd = [pref stringForKey:@"pwd"];
NSString* strlogin = [NSString stringWithFormat:@"{\"type\":\"login\",\"uid\":\"%@\",\"pwd\":\"%@\"}",strUid,strPwd];
[self.warbleSocket send:strlogin];
}
//发送心跳消息
- (void)timeChange:(NSTimer*) theTimer
{
if (self.socketReady) {
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
NSString* strUid = [pref stringForKey:@"uid"];
NSString* strPwd = [pref stringForKey:@"pwd"];
NSString *strMsg = [NSString stringWithFormat:@"{\"type\":\"chat\",\"from\":\"%@\",\"to\":\"%@\",\"msg\":\"%@\"}",strUid,strUid,@""];
[self.warbleSocket send:strMsg];
}
}
//WebSocket关闭
- (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean
{
self.socketReady = NO;
[self.tickTimer invalidate];
NSLog(@"disconnect from chat server [OK]");
[self performSelector:@selector(reconnectChatServer) withObject:nil afterDelay:10.0];
}
// SRWebSocket 收到服务器发来的消息
- (void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message
{
NSString *receiveData = http://www.mamicode.com/(NSString *)message;
NSLog(@"receive node message:%@",receiveData);
NSError *error = nil;
NSData *jsonData = http://www.mamicode.com/[receiveData dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSString* msgType = [dict objectForKey:@"type"];
NSLog(@"msgtype is %@",msgType);
if ([msgType isEqualToString:@"login"])
{
NSString* token = [dict objectForKey:@"token"];
NSUserDefaults *pref = [NSUserDefaults standardUserDefaults];
[pref setValue:token forKey:@"token"];
[self.tickTimer invalidate];
//设置定时器向服务器发送心跳消息
self.tickTimer = [NSTimer scheduledTimerWithTimeInterval:120 //秒
target:self
selector:@selector(timeChange:)
userInfo:nil
repeats:YES];
[self.tickTimer fire];
NSLog(@"connect chat server [OK]");
}
else if ([msgType isEqualToString:@"info"])
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"AppReceiveInfo" object:message];
}
else if ([msgType isEqualToString:@"notice"])
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"AppReceiveNotice" object:message];
// NoticeMessage* msg = [[NoticeMessage alloc] init];
// NSDictionary *d = [dict objectForKey:@"msg"];
// msg.strTitle = [d objectForKey:@"title"];
// msg.strContent = [d objectForKey:@"content"];
// //msg.strDate = [d objectForKey:@"date"];
//
// [arrayNotice addObject:msg];
}
else if([msgType isEqualToString:@"chat"])
{
NSString* content = [dict objectForKey:@"msg"];
if (![content isEqualToString:@""]) {
// UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"msg" message:content delegate:self cancelButtonTitle:@"ok" otherButtonTitles:nil];
// [alert show];
[[NSNotificationCenter defaultCenter] postNotificationName:@"AppReceiveNewMessage" object:message];
}
}
else if([msgType isEqualToString:@"contact"])
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"AppReceiveContact" object:message];
}
}
@end
在appdelegate中尝试解决socket掉线问题