在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 = [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 = (NSString *)message;

NSLog(@"receive node message:%@",receiveData);

NSError *error = nil;

NSData *jsonData = [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

时间: 2024-10-12 12:57:32

在appdelegate中尝试解决socket掉线问题的相关文章

尝试解决.NET Core Framework中Dns.GetHostAddressesAsync()引起的线程死锁

被这个坑坑得刻骨铭心!先爆一下 corefx 中 System.Net.Dns.GetHostAddressesAsync() 真面目. public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address) { NameResolutionPal.EnsureSocketsAreInitialized(); return Task<IPHostEntry>.Factory.FromAsync( (arg, requ

解决Socket沾包问题——C#代码

解决Socket沾包问题——C#代码 前天晚上,曾经的一个同事问我socket发送消息如果太频繁接收方就会有消息重叠,因为当时在外面,没有多加思考 第一反应还以为是多线程导致的数据不同步导致的,让他加个线程锁搞定.后来回到家慢慢思考感觉这个和加锁没啥关系,如果是多线程导致的,消息只会被覆盖呀.后来就上网搜索socket 消息重叠,后来了解到这属于socket沾包. 简单以自己的理解介绍下Socket沾包. Socket沾包简单说就是:Socket发送方 发送消息很频繁导致接收方接收到的消息是之前

C#下利用封包、拆包原理解决Socket粘包、半包问题(新手篇)

介于网络上充斥着大量的含糊其辞的Socket初级教程,扰乱着新手的学习方向,我来扼要的教一下新手应该怎么合理的处理Socket这个玩意儿. 一般来说,教你C#下Socket编程的老师,很少会教你如何解决Socket粘包.半包问题. 更甚至,某些师德有问题的老师,根本就没跟你说过Socket的粘包.半包问题是什么玩意儿. 直到有一天,你的Socket程序在传输信息时出现了你预期之外的结果(多于的信息.不完整的信息.乱码.Bug等等). 任你喊了一万遍“我擦”,依旧是不知道问题出在哪儿! 好了,不说

ubuntu中出现:程序 &#39;java&#39; 已包含在下列软件包中的解决方法

已经安装sun java 在终端中输入java,出现以下提示: 程序 'java' 已包含在下列软件包中: * default-jre * gcj-4.8-jre-headless * gcj-4.9-jre-headless * openjdk-7-jre-headless * openjdk-6-jre-headless * openjdk-8-jre-headless请尝试:apt-get install <选定的软件包> 在终端中输入javac 出现以下提示:程序 'javac' 已包

总结一下前两天刚尝试的socket编程-使用AsyncSocket

说来惭愧,搞了两年ios居然木有用过socket...初学ios的时候倒是了解过,但是两年不用,之前学的内容已经完全忘光光.于是又开始网上各种查. 用cf的socket貌似显得很拽的样子,但是实在不适合我这种领导紧逼着出项目的情况.搜了下发现目前最常用的socket库应该就是AsyncSocket了.嗯,看起来很简单,搞it~ 这个库有基于runloop和GCD两种,据我一哥们说runloop版本是基于timer机制实现异步处理,会跟scroller的滚动动画冲突.我暂时还没有验证他的说法,不过

Office 2007在安装过程中出错-解决办法

1, 可能是因为c:\program files\common files\microsoft Shared\web server Extensions\40\bin目录下缺少Fp4autl.dll,Fpencode.dll和Fp4awel.dll这三个文件导致的.可以从 windows xp的安装光盘中找到Fp40ext.cab ,把他解压出来,就可以找到这三个文件,将它们复制到bin文件夹下试试试了一下对我没用,继续搜2,运行regedit,打开注册表 找到HKEY_LOCAL_MACHIN

段错误 核心已转储尝试解决

1.在进行 gdb python r XX.py where 调试时,报出以下错误: 1)每次运行都开38个线程,是否是线程超载[New Thread 0x7ffff2fd2700 (LWP 7415)] [New Thread 0x7ffff27d1700 (LWP 7416)] [New Thread 0x7fffeffd0700 (LWP 7417)] [New Thread 0x7fffeb7cf700 (LWP 7418)] [New Thread 0x7fffe8fce700 (LW

尝试解决IIS问题一些方法

尝试解决IIS问题一些方法

python中asynchat异步socket命令/响应处理

该模块基于asyncore简化了异步客户端和服务器,并使其更容易元素处理由任意的字符串结束,或者是可变长度的的协议.它提供了抽象类async_chat,提供collect_incoming_data()和found_terminator()方法.循环和asyncore的一样,有2种信道:asyncore.dispatcher和asynchat.async_chat,可以自由混合信道.通常asyncore.dispatcher服务器通道在接收到连接请求时产生新的asynchat.async_cha