XMPP,xmpp協議
實現登入與登出
#import "AppDelegate.h"#import "XMPPFramework.h"/* * 在AppDelegate實現登入 1. 初始化XMPPStream 2. 串連到伺服器[傳一個JID] 3. 串連到服務成功後,再發送密碼授權 4. 授權成功後,發送"線上" 訊息 */@interface AppDelegate ()<XMPPStreamDelegate>{ XMPPStream *_xmppStream;}// 1. 初始化XMPPStream-(void)setupXMPPStream;// 2.串連到伺服器-(void)connectToHost;// 3.串連到服務成功後,再發送密碼授權-(void)sendPwdToHost;// 4.授權成功後,發送"線上" 訊息-(void)sendOnlineToHost;@end@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 程式一啟動就串連到主機 [self connectToHost]; return YES;}#pragma mark -私人方法#pragma mark 初始化XMPPStream-(void)setupXMPPStream{ _xmppStream = [[XMPPStream alloc] init]; // 設定代理 [_xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];}#pragma mark 串連到伺服器-(void)connectToHost{ NSLog(@"開始串連到伺服器"); if (!_xmppStream) { [self setupXMPPStream]; } // 設定登入使用者JID //resource 標識使用者登入的用戶端 iphone android XMPPJID *myJID = [XMPPJID jidWithUser:@"zhouhao" domain:@"wangzhaolu.local" resource:@"iphone" ]; _xmppStream.myJID = myJID; // 設定伺服器網域名稱 _xmppStream.hostName = @"wangzhaolu.local";//不僅可以是網域名稱,還可是IP地址 // 設定連接埠 如果伺服器連接埠是5222,可以省略 _xmppStream.hostPort = 5222; // 串連 NSError *err = nil; if(![_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&err]){ NSLog(@"%@",err); }}#pragma mark 串連到服務成功後,再發送密碼授權-(void)sendPwdToHost{ NSLog(@"再發送密碼授權"); NSError *err = nil; [_xmppStream authenticateWithPassword:@"123456" error:&err]; if (err) { NSLog(@"%@",err); }}#pragma mark 授權成功後,發送"線上" 訊息-(void)sendOnlineToHost{ NSLog(@"發送 線上 訊息"); XMPPPresence *presence = [XMPPPresence presence]; NSLog(@"%@",presence); [_xmppStream sendElement:presence];}#pragma mark -XMPPStream的代理#pragma mark 與主機串連成功-(void)xmppStreamDidConnect:(XMPPStream *)sender{ NSLog(@"與主機串連成功"); // 主機串連成功後,發送密碼進行授權 [self sendPwdToHost];}#pragma mark 與主機中斷連線-(void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error{ // 如果有錯誤,代表串連失敗 NSLog(@"與主機中斷連線 %@",error);}#pragma mark 授權成功-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{ NSLog(@"授權成功"); [self sendOnlineToHost];}#pragma mark 授權失敗-(void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error{ NSLog(@"授權失敗 %@",error);}#pragma mark -公用方法-(void)logout{ // 1." 發送 "離線" 訊息" XMPPPresence *offline = [XMPPPresence presenceWithType:@"unavailable"]; [_xmppStream sendElement:offline]; // 2. 與伺服器中斷連線 [_xmppStream disconnect];}@end
登入後的openfire
登出後的openfire
#import "ViewController.h"#import "AppDelegate.h"@interface ViewController ()@end@implementation ViewController-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{ // 做登出 AppDelegate *app = [UIApplication sharedApplication].delegate; [app logout];}@end