鏈接服務器前需準備事項:ios
1.搭建好XMPP服務器服務器
2.設置服務器地址和端口 spa
[_xmppStream setHostName:@"127.0.0.1"];code
[_xmppStream setHostPort:5222];orm
3.調用connectserver
關鍵項:blog
JID-格式必須爲 "用戶名"+"@"+"服務器地址",示例 :user@127.0.0.1string
鏈接服務器必須進行JID設置,若是尚未帳號能夠設置任意值it
具體代碼以下:io
- (BOOL)connect:(NSString*)user withpassword:(NSString*)pwd {
if (user != nil) { user = [NSString stringWithFormat:@"%@@%@",user,_xmppStream.hostName]; } if (![_xmppStream isDisconnected]) { if(_isLogined){ NSError *error = nil; password=pwd; [[self xmppStream] setMyJID:[XMPPJID jidWithString:user resource:@"ios"]]; if (![[self xmppStream] authenticateWithPassword:password error:&error]) { NSLog(@"Error authenticating: %@", error); } } return YES; } NSString *myJID = user; NSString *myPassword = pwd; if ( myPassword != nil) { password = myPassword; } if (myJID != nil) { [_xmppStream setMyJID:[XMPPJID jidWithString:myJID resource:@"ios"]]; }else{ [_xmppStream setMyJID:[XMPPJID jidWithString:_xmppStream.hostName resource:@"ios"]]; } NSError *error = nil; [_xmppStream connectWithTimeout:10 error:&error]; if(error) { NSLog(@"鏈接失敗%@",error); } return YES; }
鏈接返回的回調結果
///鏈接成功 - (void)xmppStreamDidConnect:(XMPPStream *)sender { NSLog(@"鏈接成功"); isXmppConnected = YES; if(_isLogined){ NSError *error = nil; if (![[self xmppStream] authenticateWithPassword:password error:&error]) { NSLog(@"Error authenticating: %@", error); } } } ///鏈接失敗 - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error { NSLog(@"鏈接斷開"); if (!isXmppConnected) { //DDLogError(@"Unable to connect to server. Check xmppStream.hostName"); } }
斷開鏈接
[_xmppStream disconnect];