LMY

IOS Android C# Python Silverlight Flex HTML5 WCF GIS .NET.....现已博客已移至http://blog.512z.com

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

 

连接服务器前需准备事项:

1.搭建好XMPP服务器

2.设置服务器地址和端口  

[_xmppStream setHostName:@"127.0.0.1"];

[_xmppStream setHostPort:5222];

3.调用connect

 

关键项:

  JID-格式必须为 "用户名"+"@"+"服务器地址",示例 :user@127.0.0.1

     连接服务器必须进行JID设置,如果还没有账号可以设置任意值

  

具体代码如下:

- (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];

 

posted on 2014-11-25 12:04  李明杨  阅读(4868)  评论(0编辑  收藏  举报