XMPP简单总结
最近面试被问到了一个问题,笔者当时就懵了:什么XMPP,平时怎么使用,使用过程中遇到什么问题?。
但是还是通过记忆,简单的说了一下自己所知道了,不过那并没有撒卵用,所以你懂的
XMPPFramework是一个OS X/iOS平台的开源项目,使用Objective-C实现了XMPP协议(RFC-3920),同时还提供了用于读写XML的工具,大大简化了基于XMPP的通信应用的开发。
1.关于连接的
1 //此方法在stream开始连接服务器的时候调用 2 - (void)xmppStreamDidConnect:(XMPPStream *)sender 3 //此方法在stream连接断开的时候调用 4 - (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error;
2.关于验证的
1 //验证失败后调用 2 - (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error 3 //验证成功后调用 4 - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
3.关于通信的
1 //收到消息后调用 2 - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message 3 //接受到好友状态更新 4 - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
简单实战
1. 登录和好友上下线
1.1XMPP中常用对象们
- XMPPStream:xmpp基础服务类
- XMPPRoster:好友列表类
- XMPPRosterCoreDataStorage:好友列表(用户账号)在core data中的操作类
- XMPPvCardCoreDataStorage:好友名片(昵称,签名,性别,年龄等信息)在core data中的操作类
- XMPPvCardTemp:好友名片实体类,从数据库里取出来的都是它
- xmppvCardAvatarModule:好友头像
- XMPPReconnect:如果失去连接,自动重连
- XMPPRoom:提供多用户聊天支持
- XMPPPubSub:发布订阅
1.2登录操作,也就是连接xmpp服务器
1 - (void)connect { 2 if (self.xmppStream == nil) { 3 self.xmppStream = [[XMPPStream alloc] init]; 4 [self.xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()]; 5 } 6 if (![self.xmppStream isConnected]) { 7 NSString *username = [[NSUserDefaults standardUserDefaults] objectForKey:@"username"]; 8 XMPPJID *jid = [XMPPJID jidWithUser:username domain:@"lizhen" resource:@"Ework"]; 9 [self.xmppStream setMyJID:jid]; 10 [self.xmppStream setHostName:@"10.4.125.113"]; 11 NSError *error = nil; 12 if (![self.xmppStream connect:&error]) { 13 NSLog(@"Connect Error: %@", [[error userInfo] description]); 14 } 15 } 16 }
connect成功之后会依次调用XMPPStreamDelegate的方法,首先调用
- (void)xmppStream:(XMPPStream *)sender socketDidConnect:(GCDAsyncSocket *)socket ...
然后
- (void)xmppStreamDidConnect:(XMPPStream *)sender
在该方法下面需要使用xmppStream 的authenticateWithPassword方法进行密码验证,成功的话会响应delegate的方法,就是下面这个
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
1.3上线
实现 - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender 委托方法
1 - (void)xmppStreamDidAuthenticate:(XMPPStream *)sender { 2 XMPPPresence *presence = [XMPPPresence presenceWithType:@"available"]; 3 [self.xmppStream sendElement:presence]; 4 }
1.4退出并断开连接
1 - (void)disconnect { 2 XMPPPresence *presence = [XMPPPresence presenceWithType:@"unavailable"]; 3 [self.xmppStream sendElement:presence]; 4 5 [self.xmppStream disconnect]; 6 }
1.5好友状态
获取好友状态,通过实现
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence ...
方法,当接收到 presence 标签的内容时,XMPPFramework 框架回调该方法
presence 的状态:
- available 上线
- away 离开
- do not disturb 忙碌
- unavailable 下线
1 - (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence { 2 NSString *presenceType = [presence type]; 3 NSString *presenceFromUser = [[presence from] user]; 4 if (![presenceFromUser isEqualToString:[[sender myJID] user]]) { 5 if ([presenceType isEqualToString:@"available"]) { 6 // 7 } else if ([presenceType isEqualToString:@"unavailable"]) { 8 // 9 } 10 } 11 }
2. 接收消息和发送消息
2.1接收消息
通过实现
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message;
当接收到 message 标签的内容时,XMPPFramework 框架回调该方法
根据 XMPP 协议,消息体的内容存储在标签 body 内
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message { NSString *messageBody = [[message elementForName:@"body"] stringValue]; }
2.2发送消息
发送消息,我们需要根据 XMPP 协议,将数据放到标签内
1 - (void)sendMessage:(NSString *) message toUser:(NSString *) user { 2 NSXMLElement *body = [NSXMLElement elementWithName:@"body"]; 3 [body setStringValue:message]; 4 NSXMLElement *message = [NSXMLElement elementWithName:@"message"]; 5 [message addAttributeWithName:@"type" stringValue:@"chat"]; 6 NSString *to = [NSString stringWithFormat:@"%@@example.com", user]; 7 [message addAttributeWithName:@"to" stringValue:to]; 8 [message addChild:body]; 9 [self.xmppStream sendElement:message]; 10 }
3. 获取好友信息和删除好友
3.1好友列表和好友名片
1 [_xmppRoster fetchRoster];//获取好友列表 2 //获取到一个好友节点 3 - (void)xmppRoster:(XMPPRoster *)sender didRecieveRosterItem:(NSXMLElement *)item 4 //获取完好友列表 5 - (void)xmppRosterDidEndPopulating:(XMPPRoster *)sender 6 //到服务器上请求联系人名片信息 7 - (void)fetchvCardTempForJID:(XMPPJID *)jid; 8 //请求联系人的名片,如果数据库有就不请求,没有就发送名片请求 9 - (void)fetchvCardTempForJID:(XMPPJID *)jid ignoreStorage:(BOOL)ignoreStorage; 10 //获取联系人的名片,如果数据库有就返回,没有返回空,并到服务器上抓取 11 - (XMPPvCardTemp *)vCardTempForJID:(XMPPJID *)jid shouldFetch:(BOOL)shouldFetch; 12 //更新自己的名片信息 13 - (void)updateMyvCardTemp:(XMPPvCardTemp *)vCardTemp; 14 //获取到一盒联系人的名片信息的回调 15 - (void)xmppvCardTempModule:(XMPPvCardTempModule *)vCardTempModule 16 didReceivevCardTemp:(XMPPvCardTemp *)vCardTemp 17 forJID:(XMPPJID *)jid
3.2添加好友
1 //name为用户账号 2 - (void)XMPPAddFriendSubscribe:(NSString *)name 3 { 4 //XMPPHOST 就是服务器名, 主机名 5 XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",name,XMPPHOST]]; 6 //[presence addAttributeWithName:@"subscription" stringValue:@"好友"]; 7 [xmppRoster subscribePresenceToUser:jid]; 8 9 }
3.3收到添加好友的请求
1 - (void)xmppRoster:(XMPPRoster *)sender didReceivePresenceSubscriptionRequest:(XMPPPresence *)presence 2 { 3 //取得好友状态 4 NSString *presenceType = [NSString stringWithFormat:@"%@", [presence type]]; //online/offline 5 //请求的用户 6 NSString *presenceFromUser =[NSString stringWithFormat:@"%@", [[presence from] user]]; 7 NSLog(@"presenceType:%@",presenceType); 8 9 NSLog(@"presence2:%@ sender2:%@",presence,sender); 10 11 XMPPJID *jid = [XMPPJID jidWithString:presenceFromUser]; 12 //接收添加好友请求 13 [xmppRoster acceptPresenceSubscriptionRequestFrom:jid andAddToRoster:YES]; 14 15 }
3.4删除好友
1 //删除好友,name为好友账号 2 - (void)removeBuddy:(NSString *)name 3 { 4 XMPPJID *jid = [XMPPJID jidWithString:[NSString stringWithFormat:@"%@@%@",name,XMPPHOST]]; 5 6 [self xmppRoster] removeUser:jid]; 7 }
4. 聊天室
初始化聊天室
1 XMPPJID *roomJID = [XMPPJID jidWithString:ROOM_JID]; 2 3 xmppRoom = [[XMPPRoom alloc] initWithRoomStorage:self jid:roomJID]; 4 5 [xmppRoom activate:xmppStream]; 6 [xmppRoom addDelegate:self delegateQueue:dispatch_get_main_queue()];
创建聊天室成功
- (void)xmppRoomDidCreate:(XMPPRoom *)sender { DDLogInfo(@"%@: %@", THIS_FILE, THIS_METHOD); }
加入聊天室,使用昵称
[xmppRoom joinRoomUsingNickname:@"quack" history:nil];
获取聊天室信息
1 - (void)xmppRoomDidJoin:(XMPPRoom *)sender 2 { 3 [xmppRoom fetchConfigurationForm]; 4 [xmppRoom fetchBanList]; 5 [xmppRoom fetchMembersList]; 6 [xmppRoom fetchModeratorsList]; 7 }
如果房间存在,会调用委托
// 收到禁止名单列表
- - (void)xmppRoom:(XMPPRoom *)sender didFetchBanList:(NSArray *)items;
// 收到好友名单列表
- - (void)xmppRoom:(XMPPRoom *)sender didFetchMembersList:(NSArray *)items;
// 收到主持人名单列表
- - (void)xmppRoom:(XMPPRoom *)sender didFetchModeratorsList:(NSArray *)items;
房间不存在,调用委托
- - (void)xmppRoom:(XMPPRoom *)sender didNotFetchBanList:(XMPPIQ *)iqError;
- - (void)xmppRoom:(XMPPRoom *)sender didNotFetchMembersList:(XMPPIQ *)iqError;
- - (void)xmppRoom:(XMPPRoom *)sender didNotFetchModeratorsList:(XMPPIQ *)iqError;
离开房间
[xmppRoom deactivate:xmppStream];
XMPPRoomDelegate的其他代理方法:
离开聊天室
1 - (void)xmppRoomDidLeave:(XMPPRoom *)sender 2 { 3 DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 4 }
新人加入群聊
1 - (void)xmppRoom:(XMPPRoom *)sender occupantDidJoin:(XMPPJID *)occupantJID 2 { 3 DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 4 }
有人退出群聊
1 - (void)xmppRoom:(XMPPRoom *)sender occupantDidLeave:(XMPPJID *)occupantJID 2 { 3 DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 4 }
有人在群里发言
1 - (void)xmppRoom:(XMPPRoom *)sender didReceiveMessage:(XMPPMessage *)message fromOccupant:(XMPPJID *)occupantJID 2 { 3 DDLogVerbose(@"%@: %@", THIS_FILE, THIS_METHOD); 4 }
5. 消息回执
这个是XEP-0184协议的内容
发送消息时附加回执请求
代码实现
1 NSString *siID = [XMPPStream generateUUID]; 2 //发送消息 3 XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:jid elementID:siID]; 4 NSXMLElement *receipt = [NSXMLElement elementWithName:@"request" xmlns:@"urn:xmpp:receipts"]; 5 [message addChild:receipt]; 6 [message addBody:@"测试"]; 7 [self.xmppStream sendElement:message];
收到回执请求的消息,发送回执
代码实现
1 - (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message 2 { 3 //回执判断 4 NSXMLElement *request = [message elementForName:@"request"]; 5 if (request) 6 { 7 if ([request.xmlns isEqualToString:@"urn:xmpp:receipts"])//消息回执 8 { 9 //组装消息回执 10 XMPPMessage *msg = [XMPPMessage messageWithType:[message attributeStringValueForName:@"type"] to:message.from elementID:[message attributeStringValueForName:@"id"]]; 11 NSXMLElement *recieved = [NSXMLElement elementWithName:@"received" xmlns:@"urn:xmpp:receipts"]; 12 [msg addChild:recieved]; 13 14 //发送回执 15 [self.xmppStream sendElement:msg]; 16 } 17 }else 18 { 19 NSXMLElement *received = [message elementForName:@"received"]; 20 if (received) 21 { 22 if ([received.xmlns isEqualToString:@"urn:xmpp:receipts"])//消息回执 23 { 24 //发送成功 25 NSLog(@"message send success!"); 26 } 27 } 28 } 29 30 //消息处理 31 //... 32 }
6. 添加AutoPing
为
了监听服务器是否有效,增加心跳监听。用XEP-0199协议,在XMPPFrameWork框架下,封装了 XMPPAutoPing 和
XMPPPing两个类都可以使用,因为XMPPAutoPing已经组合进了XMPPPing类,所以XMPPAutoPing使用起来更方便。
1 //初始化并启动ping 2 -(void)autoPingProxyServer:(NSString*)strProxyServer 3 { 4 _xmppAutoPing = [[XMPPAutoPingalloc] init]; 5 [_xmppAutoPingactivate:_xmppStream]; 6 [_xmppAutoPingaddDelegate:selfdelegateQueue: dispatch_get_main_queue()]; 7 _xmppAutoPing.respondsToQueries = YES; 8 _xmppAutoPing.pingInterval=2;//ping 间隔时间 9 if (nil != strProxyServer) 10 { 11 _xmppAutoPing.targetJID = [XMPPJID jidWithString: strProxyServer ];//设置ping目标服务器,如果为nil,则监听socketstream当前连接上的那个服务器 12 } 13 } 14 //卸载监听 15 [_xmppAutoPing deactivate]; 16 [_xmppAutoPing removeDelegate:self]; 17 _xmppAutoPing = nil; 18 //ping XMPPAutoPingDelegate的委托方法: 19 - (void)xmppAutoPingDidSendPing:(XMPPAutoPing *)sender 20 { 21 NSLog(@"- (void)xmppAutoPingDidSendPing:(XMPPAutoPing *)sender"); 22 } 23 - (void)xmppAutoPingDidReceivePong:(XMPPAutoPing *)sender 24 { 25 NSLog(@"- (void)xmppAutoPingDidReceivePong:(XMPPAutoPing *)sender"); 26 } 27 28 - (void)xmppAutoPingDidTimeout:(XMPPAutoPing *)sender 29 { 30 NSLog(@"- (void)xmppAutoPingDidTimeout:(XMPPAutoPing *)sender"); 31 }