Connect gloox to the server (an XMPP Library)

Source: Internet
Author: User

Connect gloox to the server

Before using gloox, it is necessary to mention the XMPP protocol.

XMPP is a standard Internet-based instant messaging protocol. It uses XML technology to transmit instant messages in text mode. Supports dynamic custom extended applications. Compared with traditional network protocols, such as QQ, XMPP is not a binary-based protocol, but a text Method Based on XML technology. That is to say, if encryption technology is not used, you can directly view the sent messages. XMPP protocol defines some XML node keywords to indicate message sending information and can be effectively combined with other protocols. In general, XMPP is a good standard for quasi-real-time messaging. If you allow, you can define a protocol as long as the keyword of the XML node is agreed and various situations in message exchange are considered. However, if there are no special cases, the XMPP protocol standard should generally be used for message exchange. At the same time, you can expand some nodes according to your specific application and according to your own expansion conventions, resolution.

So what is gloox used? The problem is very simple. As mentioned above, XMPP is only a protocol and an agreement, but it does not provide implementation methods. That is to say, the keywords defined by the XMPP protocol and the sent messages need to be implemented. As long as the XMPP protocol is used, messages can be interconnected. Gloox is a development kit that implements such a protocol. We can use this development kit to develop our own applications.

So how does gloox implement the XMPP protocol? In fact, its underlying layer is a socket that sends and receives data, and then parses and encapsulates the data in XML format. If allowed, you can perform socket communication by yourself. You only need to connect to the XMPP server and send and receive messages. Then, parse the received messages into XML format, then obtain the required information. For sending a message, the text message to be sent is encapsulated into a key node defined by the XMPP protocol, and then sent using socket.

Of course, there is no problem in receiving and sending messages according to the XMPP protocol through socket communication, but to be honest, it is difficult to grasp the socket communication, although it looks like there are just a few APIs, it takes time to make good use of them. Gloox has already done this step. Why should we reinvent the wheel? Gloox has implemented socket communication with the XMPP server at the underlying layer, and provides a secondary development interface, so that we don't have to consider the underlying data connection and other issues. Why not?

With this understanding, you can understand and understand gloox's API for secondary development.

This time, we will start from the basic connection with the XMPP protocol server, step by step.

In fact, in the downloaded gloox Development Kit, Src contains two directories: Example and test. The directory contains examples for use. You can refer to the example to see how to use it. I also use these examples, read the comments in the source code, understand some things, and then sort them out. I think there are some gains, so I will write it out.

To connect to a server, you usually need the following information: server address (domain name or IP address), server port number, user account, and user password. In XMPP protocol, the recommended Port Number of the server is 5222. If there is no other need, we recommend that you use this port number. The alias of an XMPP user account is jid. jid uniquely identifies an independent object or entity for instant messaging and online status information communication, and is compatible with other instant messaging systems (such as MSN) the corresponding entity ID and its online status information. The syntax rule is: [Node″@″] Domain name ["/" resource], where the length of each domain cannot exceed 1 023 bytes, the total length is up to 3071 bytes. From the definition of jid, we can see that to connect to the server, the jid already contains the server address. If the port number is 5222 by default, you do not need to provide the server address and port. Instead, you can connect to the server through jid.

The server I use is openfire. Therefore, I directly created several users through the openfire Management Terminal. Of course, gloox provides APIs for registering accounts, changing passwords, and deleting accounts on the server, however, I will not do this function for the time being, because I think it is of little significance in actual project development, and if I can understand other functions, let's take a look at the register example in the gloox source code. There should be no problem.

Now let's assume that I have registered a user name:TestThe password is "test". I will use this account to connect to the server, that is, login.

Assume that you have a class named messagetest and a method named start () in this class. If you intend to use this method for login, the login code is as follows (the Code contains explanations ):

 

# Include "client. H"

# Include "connectionlistener. H"

# Include "Disco. H"

# Include "stanza. H"

# Include "gloox. H"

# Include "lastactivity. H"

# Include "connectiontcpclient. H"

Using namespacegloox;

 

# Ifndef _ Win32

# Include <unistd. h>

# Endif

 

# Include <stdio. h>

# Include <string>

 

# If defined (win32) | defined (_ Win32)

# Include <windows. h>

# Endif

// Connectionlistener is a connection status information // listener. When the connection is successful or fails

// Call this method in the listener. If you are not interested in the connection status information, you do not need to inherit this

// Class. The connection is definitely successful. However, generally, you need to inherit this interface and implement three of them.

// Virtual functions.

Class messagetest: Public connectionlistener

{

Public:

Messagetest (){}

Virtual ~ Messagetest (){}

Void start ()

{

// Initialize a jid, that is, the user ID.

Jid ("[email protected]/gloox ");

// Create a connection client with the password

J = new client (jid, "test ");

// Register the connection status listener. After this method is called,

// Gloox automatically calls the corresponding method in this interface implementation in the background.

J-> registerconnectionlistener (this); // The connectionlistener interface is implemented in this.

// J-> registermessagesessionhandler (this, 0 );

// Set the service. The specific meaning is unknown. Write the Service as follows (related to service discovery)

J-> disco ()-> setversion ("messagetest", gloox_version, "Linux ");

J-> disco ()-> setidentity ("client", "BOT ");

// J-> setcompression (false );

// J-> setstreammanagement (True, true );

// J-> disco ()-> addfeature (xmlns_chat_states );

// Copy the certificate authentication information.

Stringlist CA;

CA. push_back ("/path/to/cacert. CRT ");

J-> setcacerts (CA );

// When J-> connect (false) is called, the connection to the server is realized, that is, the login is completed, and the success of the connection returns // true. If the connect function parameter is set to false, the connection is not blocked. If the parameter is set to true, the connection is blocked. // The connection is J-> connect (true)

// J-> loginstance (). registerloghandler (logleveldebug, logareaall, this );

// If (J-> connect (false ))

//{

////

//}

Connectionerror Ce = connnoerror;

If (J-> connect (false ))

{

While (Ce = connnoerror)

{

Ce = J-> Recv ();

}

Printf ("Ce: % d \ n", CE );

}

Delete (j );

}

// This method is used to achieve successful connection in the connectionlistener listener interface.

Virtual void onconnect ()

{

Printf ("connection to the server successful !!! \ N ");

}

// This method indicates that the connection in the connectionlistener listener interface fails or

// Disconnect the network.

Virtual void ondisconnect (connectionerror E)

{

Printf ("disconnected: % d \ n", e );

Delete (j );

}

/// This method is used to implement a successful secure connection in the connectionlistener listener interface.

Virtual bool ontlsconnect (constcertinfo & info)

{

Return true;

}

PRIVATE:

Client * j; // client Instance Object

};

Int main (INT/* argc */, char **/* argv */) // test code

{

Messagetest * r = new messagetest ();

R-> Start ();

// Presence pre = J-> presence (); // The client object created by the client

// J-> setpresence (pre );

Delete (R );

Return 0;

}

To connect to the server, you can create a client object instance through which you can operate. In fact, to get a connection with the server is to get a client instance object. As long as you get this instance object, you have a connection with the server (provided that you have called Connect () in the client object () this method ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.