iOS開發之XMPP即時通訊簡單實現


首先搭載服務器和數據庫

搭載服務器我用的是openfire,數據庫用的是mysql

這里推薦兩個鏈接

配置mysql,用的是mysql workbench

http://justsee.iteye.com/blog/1753467

配置服務器 openfire

http://www.cnblogs.com/xiaodao/archive/2013/04/05/3000554.html

先配置好數據庫然后配置服務器

兩個都打開

 

下一個XMPP客戶端,就是用來測試的

我下的是Adium

這里下

http://xmpp.org/xmpp-software/clients/

 

然后在Adium里面添加帳號,服務器要用openfire設置好的127.0.0.1,端口用5222

這里openfire里面的服務器端口,5222是客戶端連接服務器

 

登錄成功后可以在openfire里面看到用戶已經在線

 

然后另一客戶端,我直接用代碼,覺得麻煩沒做界面

設置XMPPStream

 

然后設置帳號,至少測試,所以直接在viewDidLoad里面寫了

 

然后就是驗證密碼,下面的方法是上線,這些是代理方法,記得設置XMPPStream的代理

 

這是接受信息的方法,我沒做界面,直接打印出來接受的信息

 

如果驗證失敗的話,會調用這個方法

 

剛開始我運行一直返回XMPP驗證失敗的錯誤

 

后來在openfire查看用戶名必須帶 服務器名

例如我的帳號是test123,設置JID的用戶名就是test123@127.0.0.1

 

然后運行,沒有報錯,在openfire顯示已經在線

 

然后就可以開始聊天了,下面的是剛發的,上面的是之前的聊天記錄

發了文字和一個鏈接

然后Xcode輸出

 

即時通訊最簡單的就這樣,退出APP后openfire后台就會顯示下線

 

代碼

#import "ViewController.h"
#import "XMPP.h"


@interface ViewController ()<XMPPStreamDelegate>

@property(nonatomic,strong) XMPPStream *stream;

@end

@implementation ViewController

- (XMPPStream *)stream
{
    if (!_stream) {
        _stream = [[XMPPStream alloc] init];
        [_stream addDelegate:self delegateQueue:dispatch_get_current_queue()];
    }
    return _stream;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.stream setMyJID:[XMPPJID jidWithString:@"test123@127.0.0.1"]];
    [self.stream setHostName:@"127.0.0.1"];
    [self.stream setHostPort:5222];
    
    NSError *error = nil;
    [self.stream connectWithTimeout:1.0f error:&error];
    
    if (error) {
        NSLog(@"connectWithTimeout : %@",error);
    }
}


- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
    NSString *msg = [[message elementsForName:@"body"] lastObject];
    NSLog(@"%@",msg);
    
}

- (void)xmppStreamDidConnect:(XMPPStream *)sender
{
    NSError *error = nil;
    [self.stream authenticateWithPassword:@"test123" error:&error];
    if (error) {
        NSLog(@"authenticateWithPassword : %@",error);
    }
}


- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    XMPPPresence *presence = [XMPPPresence presence];
    [self.stream sendElement:presence];
}


- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(DDXMLElement *)error
{
    NSLog(@"didNotAuthenticate : %@",error);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM