链接服务器前需准备事项: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];