通过gloox连接到jabber服务器有两种方式:
1、以client方式建立连接;
2、以component方式建立连接。
gloox要求数据编码统一使用UTF-8.
gloox中最重要的概念应该就是事件处理(event handler)了。常用的handler有:log handler、generic tag handler、connection handler.
gloox以虚类(interface)的形式的形式给出,如PresenceHandler等。
这些handlers在接受到某消息后会以相应的形式进行处理操作。当然,在这之前要完成建立连接都操作了。
比如:我们给出一个建立连接的例子。
class MyClass : public ConnectionListener
{
public:
virtual void onConnect();
virtual bool onTLSConnect( ... );
};
void MyClass::onConnect()
{
}
bool MyClass::onTLSConnect( const CertInfo& info )
{
return true;
}
上面这个例子是摘自gloox官方api文档上的。
onTLConnect()这个函数很重要,如果你想通过tls/ssl与服务器建立连接时,则必须重写这个函数。当返回值是true时,表示信任与服务器的连接,否则,表示不信任。
上面提到了连接jabber服务器的两种方式,下面将一一介绍:
component连接编码很简单,如下:
Component *comp = new Component( ... );
comp->connect();
client连接也很简单,下面还是援引api文档上的例子。
class MyClass : public ConnectionListener, PresenceHandler
{
public:
void doSomething();
virtual void handlePresence( ... );
virtual void onConnect();
virtual bool onTLSConnect( const CertInfo& info );
};
void MyClass::doSomething()
{
JID jid( "jid@server/resource" );
Client *client = new Client( jid, "password" );
client->registerConnectionListener( this );
client->registerPresenceHandler( this );
client->connect();
}
void MyClass::onConnect()
{
}
bool MyClass::onTLSConnect( const CertInfo& info )
{
}
void MyClass::handlePresence( Stanza *stanza )
{
}
下面给出一个完整的连接例子,在VS2008环境下测试成功。
#include "registration.h" // gloox headers #include "client.h" #include "connectionlistener.h" include "presencehandler.h"
using namespace gloox;
class ConnectionDemo : public ConnectionListener,PresenceHandler { public: void doSomething(); virtual void handlePresence(Stanza* stanza); virtual void onConnect(); virtual bool onTLSConnect(const CertInfo& info); virtual void gloox::ConnectionListener::onDisconnect(gloox::ConnectionError); };
void ConnectionDemo::doSomething() { JID jid( "" ); Client *client = new Client( jid, "891228" ); client->registerConnectionListener( this ); client->registerPresenceHandler( this ); client->connect();
}
void ConnectionDemo::handlePresence(Stanza* stanza) { printf("正在处理出席事件...\n"); }
void ConnectionDemo::onConnect() { printf("正在建立连接...\n"); }
bool ConnectionDemo::onTLSConnect(const CertInfo& info) { printf("信任与服务器建立的TLS连接.\n"); return true; }
void ConnectionDemo::onDisconnect(gloox::ConnectionError) { printf("断开连接..."); }
int main( int argc, char* argv[] ) { ConnectionDemo cd; cd.doSomething(); return 0; } |
PS:gloox没有(也不会)支持的连接方式是使用5223端口,即SSL加密之前,任何XML发送的,因为它不是标准的XMPP协议。
今天先写到这里。
阅读(1806) | 评论(4) | 转发(0) |