一:搭建一個即時聊天服務器推薦一下兩種,搭建方法大家自行百度一下,有很多詳細的教程
Openfire 使用 Java 語言編寫,比較容易上手,
ejabberd 使用 Erlang 語言編寫,是一款非常知名的 Erlang 開源項目,
二:開始進行登錄操作
1、新建一個 XMPPStream 對象,添加委托
添加委托方法 - (void)addDelegate:(id)delegate delegateQueue:(dispatch_queue_t)delegateQueue
參數 delegateQueue 為委托回調所使用的 GCD 隊列,dispatch_get_main_queue() 獲取主線程 GCD 隊列
2、設置 JID 和 主機名
JID 一般由三部分構成:用戶名,域名和資源名,例如 [email protected]/Anthony
如果沒有設置主機名,則使用 JID 的域名作為主機名
端口號是可選的,默認是 5222
3、連接
- (void)connect { if (self.xmppStream == nil) { self.xmppStream = [[XMPPStream alloc] init]; [self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()]; } if (![self.xmppStream isConnected]) { NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@username]; XMPPJID *jid = [XMPPJID jidWithUser:username domain:@lizhen resource:@Ework]; [self.xmppStream setMyJID:jid]; [self.xmppStream setHostName:@10.4.125.113]; NSError *error = nil; if (![self.xmppStream connect:&error]) { NSLog(@Connect Error: %@, [[error userInfo] description]); } } }
身份認證
實現 - (void)xmppStreamDidConnect:(XMPPStream *)sender 委托方法
連接服務器成功後,回調該方法
This method is called after the XML stream has been fully opened. More precisely, this method is called after an opening
身份認證方法 - (BOOL)authenticateWithPassword:(NSString *)inPassword error:(NSError **)errPtr
- (void)xmppStreamDidConnect:(XMPPStream *)sender { NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:@password]; NSError *error = nil; if (![self.xmppStream authenticateWithPassword:password error:&error]) { NSLog(@Authenticate Error: %@, [[error userInfo] description]); } }
上線
實現 - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender 委托方法
身份認證成功後,回調該方法
This method is called after authentication has successfully finished.
If authentication fails for some reason, the xmppStream:didNotAuthenticate: method will be called instead.
新建一個 XMPPPresence 對象,類型為 available,發送!
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender { XMPPPresence *presence = [XMPPPresence presenceWithType:@available]; [self.xmppStream sendElement:presence]; }
退出並斷開連接
新建一個 XMPPPresence 對象,類型為 unavailable,發送!
斷開連接
- (void)disconnect { XMPPPresence *presence = [XMPPPresence presenceWithType:@unavailable]; [self.xmppStream sendElement:presence]; [self.xmppStream disconnect]; }