XMPP使用---XMPPStream( 二)

2 篇文章 0 订阅
2 篇文章 0 订阅


仿微信Demo下载地址http://download.csdn.net/download/leewolf130/7035795:点击打开链接

仿微信服务器端源码:http://download.csdn.net/detail/leewolf130/7035771点击打开链接


相关文章(一)http://blog.csdn.net/leewolf130/article/details/21240561

相关文章(二)http://blog.csdn.net/leewolf130/article/details/21240637

相关文章(三)http://blog.csdn.net/leewolf130/article/details/21240757


转载地址http://blog.csdn.net/abel_tu/article/details/12618677

上篇对XMPP进行了介绍,以及如果运行第一个XMPP应用程序,现在这篇就来介绍如何使用XMPPFramework第二方库和服务器进行连接。



[html] view plaincopy


  1. #pragma mark Private  
  2.   初始化 XMPPStream   
  3.   
  4. - (void)setupStream  
  5. {  
  6.   
  7.     xmppStream = [[XMPPStream alloc] init];  
  8.       
  9.     #if !TARGET_IPHONE_SIMULATOR{  
  10.         //   设置后台也进行连接  
  11.         xmppStream.enableBackgroundingOnSocket = YES;  
  12.     }  
  13.     #endif  
  14.       
  15.     // 创建XMPPStream重联  
  16.       
  17.     xmppReconnect = [[XMPPReconnect alloc] init];  
  18.       
  19.     // 创建XMPP花名册.XMPPRosterCoreDataStorage为xmppRoster的代理,里面实现了coreData的保存。  
  20.     xmppRosterStorage = [[XMPPRosterCoreDataStorage alloc] init];  
  21.     xmppRoster = [[XMPPRoster alloc] initWithRosterStorage:xmppRosterStorage];  
  22.       
  23.     xmppRoster.autoFetchRoster = YES;  
  24.     xmppRoster.autoAcceptKnownPresenceSubscriptionRequests = YES;  
  25.       
  26.     // Setup vCard support  
  27.     // 创建支持vCard  
  28.     xmppvCardStorage = [XMPPvCardCoreDataStorage sharedInstance];  
  29.     xmppvCardTempModule = [[XMPPvCardTempModule alloc] initWithvCardStorage:xmppvCardStorage];  
  30.       
  31.     xmppvCardAvatarModule = [[XMPPvCardAvatarModule alloc] initWithvCardTempModule:xmppvCardTempModule];  
  32.       
  33.     // Setup capabilities  
  34.     //   
  35.     xmppCapabilitiesStorage = [XMPPCapabilitiesCoreDataStorage sharedInstance];  
  36.         xmppCapabilities = [[XMPPCapabilities alloc] initWithCapabilitiesStorage:xmppCapabilitiesStorage];  
  37.   
  38.         xmppCapabilities.autoFetchHashedCapabilities = YES;  
  39.         xmppCapabilities.autoFetchNonHashedCapabilities = NO;  
  40.   
  41.     // Activate xmpp modules  
  42.   
  43.     [xmppReconnect         activate:xmppStream];  
  44.     [xmppRoster            activate:xmppStream];  
  45.     [xmppvCardTempModule   activate:xmppStream];  
  46.     [xmppvCardAvatarModule activate:xmppStream];  
  47.     [xmppCapabilities      activate:xmppStream];  
  48.   
  49.     [xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];  
  50.     [xmppRoster addDelegate:self delegateQueue:dispatch_get_main_queue()];  
  51. }  
  52.   
  53. // 取消注册  
  54. - (void)teardownStream  
  55. {  
  56.     [xmppStream removeDelegate:self];  
  57.     [xmppRoster removeDelegate:self];  
  58.       
  59.     [xmppReconnect         deactivate];  
  60.     [xmppRoster            deactivate];  
  61.     [xmppvCardTempModule   deactivate];  
  62.     [xmppvCardAvatarModule deactivate];  
  63.     [xmppCapabilities      deactivate];  
  64.       
  65.     [xmppStream disconnect];  
  66.       
  67.     xmppStream = nil;  
  68.     xmppReconnect = nil;  
  69.     xmppRoster = nil;  
  70.     xmppRosterStorage = nil;  
  71.     xmppvCardStorage = nil;  
  72.     xmppvCardTempModule = nil;  
  73.     xmppvCardAvatarModule = nil;  
  74.     xmppCapabilities = nil;  
  75.     xmppCapabilitiesStorage = nil;  
  76. }  
  77.   
  78. // 向服务器发送上线操作.  
  79. - (void)goOnline  
  80. {  
  81.     XMPPPresence *presence = [XMPPPresence presence]; // type默认为available  
  82.     [[self xmppStream] sendElement:presence];  
  83. }  
  84.   
  85. // 向服务器发送下线操作  
  86. - (void)goOffline  
  87. {  
  88.     XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"];  
  89.     [[self xmppStream] sendElement:presence];  
  90. }  
  91.   
  92.   
  93. #pragma mark Connect/disconnect  
  94.   连接服务器  
  95. - (BOOL)connect  
  96. {  
  97.     if (![xmppStream isDisconnected]) {     // 如果已经连接  
  98.              return YES;  
  99.     }  
  100.   
  101.     NSString *myJID = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyJID];  
  102.     NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:kXMPPmyPassword];  
  103.       
  104.     if (myJID == nil || myPassword == nil) {  
  105.         return NO;  
  106.     }  
  107.   
  108.     [xmppStream setMyJID:[XMPPJID jidWithString:myJID]];// 设置账号  
  109.         // 设置服务器域名,如果不设置默认为账号后面的域名//   
  110.         // [xmppStream setHostName:@""];  
  111.         // 设置端口号,如果不设置默认为5222  
  112.         // [xmppStreamsetHostPort:5222];  
  113.     password = myPassword;  
  114.   
  115.     NSError *error = nil;  
  116.     if (![xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&error]){  
  117.         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error connecting"   
  118.                                                             message:@"See console for error details."   
  119.                                                            delegate:nil   
  120.                                                   cancelButtonTitle:@"Ok"   
  121.                                                   otherButtonTitles:nil];  
  122.         [alertView show];  
  123.   
  124.         DDLogError(@"Error connecting: %@", error);  
  125.   
  126.         return NO;  
  127.     }  
  128.   
  129.     return YES;  
  130. }  
  131.   
  132. // 取消连接  
  133. - (void)disconnect  
  134. {  
  135.     [self goOffline];  
  136.     [xmppStream disconnect];  
  137. }  
  138.   
  139.   
  140. #pragma mark XMPPStream Delegate  
  141.   
  142.   
  143. // 正在连接中….  
  144. - (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket   
  145. {  
  146.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  147. }  
  148.   
  149. - (void)xmppStream:(XMPPStream *)sender willSecureWithSettings:(NSMutableDictionary *)settings  
  150. {  
  151.     if (allowSelfSignedCertificates){  
  152.         [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];  
  153.     }  
  154.       
  155.     if (allowSSLHostNameMismatch)  
  156.     {  
  157.         [settings setObject:[NSNull null] forKey:(NSString *)kCFStreamSSLPeerName];  
  158.     }else{  
  159.         // Google does things incorrectly (does not conform to RFC).  
  160.         // Because so many people ask questions about this (assume xmpp framework is broken),  
  161.         // I've explicitly added code that shows how other xmpp clients "do the right thing"  
  162.         // when connecting to a google server (gmail, or google apps for domains).  
  163.           
  164.         NSString *expectedCertName = nil;  
  165.           
  166.         NSString *serverDomain = xmppStream.hostName;  
  167.         NSString *virtualDomain = [xmppStream.myJID domain];  
  168.           
  169.         if ([serverDomain isEqualToString:@"talk.google.com"]){  
  170.             if ([virtualDomain isEqualToString:@"gmail.com"]){  
  171.                 expectedCertName = virtualDomain;  
  172.             }else{  
  173.                 expectedCertName = serverDomain;  
  174.             }  
  175.         }else if (serverDomain == nil){  
  176.             expectedCertName = virtualDomain;  
  177.         }else{  
  178.             expectedCertName = serverDomain;  
  179.         }  
  180.           
  181.         if (expectedCertName){  
  182.             [settings setObject:expectedCertName forKey:(NSString *)kCFStreamSSLPeerName];  
  183.         }  
  184.     }  
  185. }  
  186.   
  187. - (void)xmppStreamDidSecure:(XMPPStream *)sender  
  188. {  
  189. }  
  190.   
  191. // 成功连接服务器  
  192. - (void)xmppStreamDidConnect:(XMPPStream *)sender  
  193. {  
  194.     NSError *error = nil;  
  195.     // 对用户进行认证  
  196.     if (![[self xmppStream] authenticateWithPassword:password error:&error]){  
  197.         DDLogError(@"Error authenticating: %@", error);  
  198.     }  
  199. }  
  200.   
  201. // 认证成功  
  202. - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender  
  203. {  
  204.     [self goOnline];  
  205. }  
  206.   
  207. // 认证失败  
  208. - (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error  
  209. {  
  210. }  
  211.   
  212. - (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq  
  213. {  
  214.     return NO;  
  215. }  
  216.   
  217. // 收到消息  
  218. - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message  
  219. {  
  220.   
  221.     // A simple example of inbound message handling.  
  222.   
  223.     if ([message isChatMessageWithBody]){  
  224.         XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[message from]  
  225.                                                                  xmppStream:xmppStream  
  226.                                                        managedObjectContext:[self managedObjectContext_roster]];  
  227.           
  228.         NSString *body = [[message elementForName:@"body"] stringValue];  
  229.         NSString *displayName = [user displayName];  
  230.   
  231.         if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive){  
  232.             UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName  
  233.                                                               message:body   
  234.                                                              delegate:nil   
  235.                                                     cancelButtonTitle:@"Ok"   
  236.                                                     otherButtonTitles:nil];  
  237.             [alertView show];  
  238.         }else{  
  239.             // We are not active, so use a local notification instead  
  240.             UILocalNotification *localNotification = [[UILocalNotification alloc] init];  
  241.             localNotification.alertAction = @"Ok";  
  242.             localNotification.alertBody = [NSString stringWithFormat:@"From: %@\n\n%@",displayName,body];  
  243.   
  244.             [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];  
  245.         }  
  246.     }  
  247. }  
  248.   
  249. // 收到好友上线下线,正在输入等一些消息  
  250. - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence  
  251. {  
  252.     DDLogVerbose(@"%@: %@ - %@", THIS_FILE, THIS_METHOD, [presence fromStr]);  
  253. }  
  254.   
  255. // 收到错误消息  
  256. - (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error  
  257. {  
  258.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  259. }  
  260.   
  261. // 连接出错  
  262. - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error  
  263. {  
  264.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  265.       
  266.     if (!isXmppConnected)  
  267.     {  
  268.         DDLogError(@"Unable to connect to server. Check xmppStream.hostName");  
  269.     }  
  270. }  
  271.   
  272.   
  273. #pragma mark XMPPRosterDelegate  
  274.   
  275.   
  276. // 收到花名册  
  277. - (void)xmppRoster:(XMPPRoster *)sender didReceiveBuddyRequest:(XMPPPresence *)presence  
  278. {  
  279.     DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD);  
  280.       
  281.     XMPPUserCoreDataStorageObject *user = [xmppRosterStorage userForJID:[presence from]  
  282.                                                              xmppStream:xmppStream  
  283.                                                    managedObjectContext:[self managedObjectContext_roster]];  
  284.       
  285.     NSString *displayName = [user displayName];  
  286.     NSString *jidStrBare = [presence fromStr];  
  287.     NSString *body = nil;  
  288.       
  289.     if (![displayName isEqualToString:jidStrBare]){  
  290.         body = [NSString stringWithFormat:@"Buddy request from %@ <%@>", displayName, jidStrBare];  
  291.     }else{  
  292.         body = [NSString stringWithFormat:@"Buddy request from %@", displayName];  
  293.     }  
  294.       
  295.       
  296.     if ([[UIApplication sharedApplication] applicationState] == UIApplicationStateActive){  
  297.         UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:displayName  
  298.                                                             message:body   
  299.                                                            delegate:nil   
  300.                                                   cancelButtonTitle:@"Not implemented"  
  301.                                                   otherButtonTitles:nil];  
  302.         [alertView show];  
  303.     } else {  
  304.         // We are not active, so use a local notification instead  
  305.         UILocalNotification *localNotification = [[UILocalNotification alloc] init];  
  306.         localNotification.alertAction = @"Not implemented";  
  307.         localNotification.alertBody = body;  
  308.           
  309.         [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];  
  310.     }  
  311.       
  312. }  
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值