上篇对XMPP进行了介绍,以及如果运行第一个XMPP应用程序,现在这篇就来介绍如何使用XMPPFramework第二方库和服务器进行连接。
初始化一个XMPPStream
xmppStream = [[XMPPStreamalloc]init];现在我们再来看看 [xmppStreamaddDelegate:selfdelegateQueue:dispatch_get_current_queue()];
建立连接
- (BOOL)connect
{
if (![xmppStreamisDisconnected]) {
returnYES;
}
NSString *myJID =@"xxx@xxx.xxx";
NSString *myPassword =@"123qaz";
// 设置用户
[xmppStreamsetMyJID:[XMPPJIDjidWithString:myJID]];
// 设置服务器域名
[xmppStreamsetHostName:@""];
// 设置端口号
[xmppStreamsetHostPort:5222];
password = myPassword;
NSError *error =nil;
if (![xmppStreamconnect:&error])
{// 如果连接出了问题(这里一般是404错误,要么是无网络,要么是不能访问)
UIAlertView *alertView = [[UIAlertViewalloc]initWithTitle:@"Error connecting"
message:@"See console for error details."
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertViewshow];
DDLogError(@"Error connecting: %@", error);
returnNO;
}
returnYES;
}
现在我们再看看XMPPStream的代理函数
// 正在连接,我们在这个函数里再对其做用户名和密码验证
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
NSError *error =nil;
if (![[selfxmppStream]authenticateWithPassword:passworderror:&error]) {
DDLogError(@"Error authenticating: %@", error);
}
}
// 用户通过验证
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
// 用户验证失败
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
// 接收消息
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
// 好友上下线通知
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence
// 连接,发送信息出错
- (void)xmppStream:(XMPPStream *)sender didReceiveError:(id)error
// 取消连接
- (void)xmppStreamDidDisconnect:(XMPPStream *)sender withError:(NSError *)error
看了XMPPStream的代理函数,我想我们大概都有了底了,至少我们现在知道如何接新收消息了。
好吧,先来看看代理函数传过来的XMPPMessage格式吧!!!
XMPPUserCoreDataStorageObject *user = [xmppRosterStorageuserForJID:[messagefrom]xmppStream:xmppStreammanagedObjectContext:[selfmanagedObjectContext_roster]];
NSString *body = [[messageelementForName:@"body"]stringValue];// 这个就是发送过来的消息
NSString *displayName = [userdisplayName];// 这个是谁发过来的
message解析就是这么简单
说了接收消息,下面来说说发送消息,
发送文件的格式为:
NSString *message = @"ha ha";
NSXMLElement *body = [NSXMLElement elementWithName:@"body"];
[body setStringValue:message];
//生成XML消息文档
NSXMLElement *mes = [NSXMLElement elementWithName:@"message"];
//消息类型
[mes addAttributeWithName:@"type" stringValue:@"chat"];
//发送给谁
[mes addAttributeWithName:@"to" stringValue:user.displayName];
//由谁发送
[mes addAttributeWithName:@"from" stringValue:@"wuliao@xxx.xxx"];
//组合
[mes addChild:body];
//发送消息
[[self appDelegate].xmppStream sendElement:mes];