您的位置:首页 > 移动开发 > IOS开发

iOS学习之XMPP登录与注销

2015-08-31 19:14 495 查看
坚持 成长 每日一篇

XMPP的登陆

使用xmpp实现登陆的步骤如下

1.初始化XMPPStream

-(void)setupXMPPStream{
_xmppStream = [[XMPPStream alloc] init];
//设置代理
[_xmppStream addDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)];
}


2.创建一个XMPPJID对象,并连接服务器(这里只是链接并没有登录)如果链接成功会回调-(void)xmppStreamDidConnect:(XMPPStream *)sender的代理方法;

-(void)connectToHost{
NSLog(@"开始连接到服务器");
if (!_xmppStream) {
[self setupXMPPStream];
}
// 设置将要登录用户的JID
//resource 标识用户登录的客户端是什么类型的如 iphone android,domain可以传nil则使用服务器域名
XMPPJID *myJID = [XMPPJID jidWithUser:@"wangwu" domain:@"teacher.local" resource:@"iphone" ];
_xmppStream.myJID = myJID;

// 设置服务器域名
_xmppStream.hostName = @"teacher.local";//不仅可以是域名,还可是IP地址

// 设置端口 如果服务器端口是5222,可以省略
_xmppStream.hostPort = 5222;

// 连接
NSError *err = nil;
if(![_xmppStream connectWithTimeout:XMPPStreamTimeoutNone error:&err]){
NSLog(@"%@",err);
}

}


3.连接到服务成功后,再发送密码授权,告诉服务器开始登录

-(void)sendPwdToHost{
NSLog(@"送密码授权");
NSError *err = nil;
[_xmppStream authenticateWithPassword:@"123456" error:&err];
if (err) {
NSLog(@"%@",err);
}
}


sendPwdToHost在-(void)xmppStreamDidConnect:(XMPPStream *)sender回调函数里调用

-(void)xmppStreamDidConnect:(XMPPStream *)sender{
NSLog(@"与主机连接成功");
// 主机连接成功后,发送密码进行授权
[self sendPwdToHost];
}


授权成功回调-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender函数

授权失败回调-(void)xmppStream:(XMPPStream )sender didNotAuthenticate:(DDXMLElement )error函数

4.授权成功后,发送”在线” 消息,告诉服务器刷新用户在线状态

-(void)xmppStreamDidAuthenticate:(XMPPStream *)sender{
NSLog(@"授权成功");
//想服务器发送登录消息
[self sendOnlineToHost];
}


-(void)sendOnlineToHost{
NSLog(@"发送 在线 消息");
XMPPPresence *presence = [XMPPPresence presence];
NSLog(@"%@",presence);
[_xmppStream sendElement:presence];
}


XMPP用户注销

用户注销步骤相对简单只需发送离线消息并断开连接,方便下一个用户登录

-(void)sendOffLineToHost{
// 1." 发送 "离线" 消息",不设置type的默认是available
XMPPPresence *offline = [XMPPPresence presenceWithType:@"unavailable"];
[_xmppStream sendElement:offline];
// 2. 与服务器断开连接
[_xmppStream disconnect];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: