首页 > 代码库 > xmpp协议的使用

xmpp协议的使用

最近学了xmpp感觉学的很乱,想好好整理一下,于是今天找了点时间,把xmpp的搭建和工程的创建一步步进行说明

第一步 xmpp环境的搭建

所需的工具包

搭建环境需要如下所示的包

1 安装xampp-osx 安装完后,运行选择Manager Services 启动所有的Service

注:如果启动失败,请确保安装了javaForOSX2014,也就是java的类库(对于之前没有安装java环境的电脑来说,首先请安装java的环境)

2 当所有工程启动后,在浏览器中输入127.0.0.1,看看是否能正常访问,若能出现启动画面则证明启动成功,选择






选择phpMyAdmin进入到管理的后台首页

3 在管理的后台首页中创建一个新的数据库








例如xmpp

4 安装openfire ,安装完后进入到文件夹

选择文件-(菜单栏中的前往)->/usr进入到openfire的安装文件夹下面找到local->openfire(解锁文件,通过显示简介界面) 把里面的resource->database->openfire_mysql.sql文件拷到桌面上,再在之前的xammp后台中导入到你所见的那个数据库中

5 打开openfire进入到项目的后台中openfire 选择进入Open Admin Console输入账号和密码进入后台(admin admin)进入后进入数据库设置配置一下数据库信息

6 第六步进行代码的编写

步骤如下所示

  1导入xmpp的框架包









 导入所需的框架













注意需要修改两处

一是修改









需要加入usr/include/libxml2

二是需要加入XMPPFramework.h这个类,这个类中包含了所有的头文件

一下是对代码的分析

@implementation LOAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    [[SingleInstance shareInstance] fire];
    return YES;
}

在程序的启动过程中需要启动xmpp服务

#define kReloadDataTableWithManager @"kReloadDataTableWithManager"

#import <Foundation/Foundation.h>
#import "XMPPFramework.h"

// 第一个是添加好友的功能
// 第二个是连接的功能
@interface SingleInstance : NSObject <XMPPRosterDelegate, XMPPStreamDelegate>

// 定义一个执行顺序的信息列表
@property (nonatomic, strong) NSArray *methodList;

// 定义一个单例对象
+ (SingleInstance *)shareInstance;
// 启动服务
- (void)fire;
// 点击登陆时的方法
- (void)login:(NSString *)uid pwd:(NSString *)pwd;
// 点击注册时的方法
- (void)registerID:(NSString *)uid pwd:(NSString *)pwd;

@end
定义了一个单例类用来进行具体的操作

#import "SingleInstance.h"
// 定义了服务器的名字
#define kHostName @"127.0.0.1"
// 定义的服务器的端口号
#define kHostPort 5222

@interface SingleInstance()


@property (nonatomic, strong) XMPPStream *stream;
@property (nonatomic, strong) NSString *login_password;  // 设置登陆的密码
@property (nonatomic, strong) NSString *register_password; // 设置注册的密码

// 私有方法用来执行操作步骤
- (NSMutableDictionary *)chechDictionaryWithName:(NSString *)name time:(NSDate *)time;

@end

@implementation SingleInstance

static SingleInstance *instance = nil;

+ (SingleInstance *)shareInstance
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[SingleInstance alloc]init];
    });
    return instance;
}
// 在初始化方法中实现stream的初始化工作
- (id)init
{
    self = [super init];
    if (self) {
        self.methodList = [[NSMutableArray alloc]init];
        // 添加观察者模式,观察数据的变化操作
        [self addObserver:self forKeyPath:@"methodList" options:NSKeyValueObservingOptionPrior context:nil];
        // 初始化(stream)
        self.stream = [[XMPPStream alloc]init];
        // 设置服务器的名字
        self.stream.hostName = kHostName;
        // 设置端口号
        self.stream.hostPort = kHostPort;
        // 添加遵守 delegate 对象
        [self.stream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    }
    return self;
}
// 为了确保每次连接操作都能正常执行,先关闭再打开
- (void)fire
{
    // 断开连接
    [self.stream disconnect];
    // 启动连接
    [self.stream connectWithTimeout:-1 error:nil];
}
// 点击登陆时的方法
- (void)login:(NSString *)uid pwd:(NSString *)pwd
{
    // 登陆操作,注册id标志符
    // 参数一是服务器的名字,参数二是自定义的名字
    // 步骤1 验证用户名
    self.stream.myJID = [XMPPJID jidWithUser:uid domain:@"127.0.0.1" resource:@"iPhone100"];
    // 设置登陆的密码
    self.login_password = pwd;
    
    // 拿到数据先连接
    [self fire];
}
// 点击注册时的方法
- (void)registerID:(NSString *)uid pwd:(NSString *)pwd
{
    // 验证用户名
    self.stream.myJID = [XMPPJID jidWithUser:uid domain:@"127.0.0.1" resource:@"iPhone100"];
    self.register_password = pwd;
    [self fire];
}
- (NSMutableDictionary *)chechDictionaryWithName:(NSString *)name time:(NSDate *)time
{
    // 初始化一个字典对象,用来存放用户的名字和时间
    NSDateFormatter *formate = [[NSDateFormatter alloc]init];
    [formate setDateFormat:@"HH:mm:ss"];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"name"] = name;
    dic[@"time"] = [formate stringFromDate:time];
    return dic;
}

#pragma mark - xmppSteamDelegate

// 将要连接
- (void)xmppStreamWillConnect:(XMPPStream *)sender
{
    // 存放的是字典对象
    [[self mutableArrayValueForKey:@"methodList"] addObject:[self chechDictionaryWithName:[NSString stringWithFormat:@"%s", __FUNCTION__] time:[NSDate date]]];
    NSLog(@"%s", __FUNCTION__);
}
// 完成连接操作(在这个方法中执行具体的登录还是注册操作【】)
- (void)xmppStreamDidConnect:(XMPPStream *)sender
{

    [[self mutableArrayValueForKey:@"methodList"] addObject:[self chechDictionaryWithName:[NSString stringWithFormat:@"%s", __FUNCTION__] time:[NSDate date]]];
    NSLog(@"%s", __FUNCTION__);
    // 实行注册操作
    // 第二步执行密码的注册操作
    if (self.register_password) {
        [self.stream registerWithPassword:self.register_password error:nil];
    }
     // 实行登陆操作
     // 执行密码的登陆操作
    if (self.login_password) {
        [self.stream authenticateWithPassword:self.login_password error:nil];
    }
    self.register_password = nil;
    self.login_password = nil;
    
    
}
// 已经验证
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender
{
    [[self mutableArrayValueForKey:@"methodList"] addObject:[self chechDictionaryWithName:[NSString stringWithFormat:@"%s", __FUNCTION__] time:[NSDate date]]];
    NSLog(@"%s", __FUNCTION__);
}
// 验证失败
- (void)xmppStream:(XMPPStream *)sender didNotAuthenticate:(NSXMLElement *)error
{
    [[self mutableArrayValueForKey:@"methodList"] addObject:[self chechDictionaryWithName:[NSString stringWithFormat:@"%s", __FUNCTION__] time:[NSDate date]]];
    NSLog(@"%s", __FUNCTION__);
}
// 没有注册
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(DDXMLElement *)error
{
    [[self mutableArrayValueForKey:@"methodList"] addObject:[self chechDictionaryWithName:[NSString stringWithFormat:@"%s", __FUNCTION__] time:[NSDate date]]];
    NSLog(@"%s", __FUNCTION__);
}
// 完成注册
- (void)xmppStreamDidRegister:(XMPPStream *)sender
{
    [[self mutableArrayValueForKey:@"methodList"] addObject:[self chechDictionaryWithName:[NSString stringWithFormat:@"%s", __FUNCTION__] time:[NSDate date]]];
    NSLog(@"%s", __FUNCTION__);
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    [[NSNotificationCenter defaultCenter] postNotificationName:kReloadDataTableWithManager object:nil];
}

在MainVIewController

#import "MainViewController.h"
#import "SingleInstance.h"
@interface MainViewController ()


@end

@implementation MainViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (IBAction)registerAction:(id)sender {

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"用户注册" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
    alert.tag = 101;
    [alert show];
    
}
- (IBAction)loginAction:(id)sender {

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"用户登录" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    alert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
    
    alert.tag = 102;
    [alert show];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"测试";
    // 添加通知执行相应的操作
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_testReloadData) name:kReloadDataTableWithManager object:nil];
}
- (void)_testReloadData
{
    [self.tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{

    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [[[SingleInstance shareInstance] methodList] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Indentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:CellIdentifier];
    }
    
    NSMutableDictionary *dic = [[SingleInstance shareInstance].methodList objectAtIndex:indexPath.row];
    cell.detailTextLabel.text = [dic objectForKey:@"time"];
    cell.textLabel.text = [dic objectForKey:@"name"];
    cell.textLabel.font = [UIFont boldSystemFontOfSize:12];
    return cell;
}

#pragma mark alert Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    if ([alertView.title isEqualToString:@"用户登录"]) {
//        
//    }
//  
    if (alertView.tag == 101) {
        NSLog(@"用户注册");
        switch (buttonIndex) {
            case 1:
                [[SingleInstance shareInstance] registerID:[alertView textFieldAtIndex:0].text pwd:[alertView textFieldAtIndex:1].text];
                NSLog(@"%d", buttonIndex);
                break;
            case 0:
                NSLog(@"%d", buttonIndex);
                break;
            default:
                break;
        }
    }else
    {
        NSLog(@"用户登录");
        switch (buttonIndex) {
            case 1:
            [[SingleInstance shareInstance] login:[alertView textFieldAtIndex:0].text pwd:[alertView textFieldAtIndex:1].text];
                NSLog(@"%d", buttonIndex);
                break;
            case 0:
                NSLog(@"%d", buttonIndex);
                break;
            default:
                break;
        }
    }
}

@end