Strophe. js connects to XMPP server Openfire and Tigase for Web private chat, group chat (MUC), and xmppopenfire

Source: Internet
Author: User

Strophe. js connects to XMPP server Openfire and Tigase for Web private chat, group chat (MUC), and xmppopenfire

XMPP (Extensible Messaging and Presence Protocol) is a network instant Messaging Protocol. It is based on XML and has strong scalability, it is widely used in scenarios such as instant messaging software, online game chat, Web chat, Web message push, and mobile device message push, for example, Google's GTalk and League of legends LOL game chat modules.

Because JavaScript on the Web browser cannot directly process the TCP protocol, the XMPP server usually provides the BOSH (Bidirectional-streams Over Synchronous HTTP) interface, through the HTTP long-polling (long-polling) web browser instant chat. Strophe. js is a tool library that connects a Web browser and an XMPP server through BOSH.

XMPP protocol introduction:

The XMPP Server communicates with the client through the XML section (XML Stanza. There are three important XML Stanza types: <message>, <presence>, and <iq>.

<Message>:

The message section is used to send and receive chat messages. For example, if xxg1 @ host sends a message "hello" to xxg2 @ host, the xxg1 @ host client will send the following XML to the XMPP server, and the server will push it to the xxg2 @ host client. The from attribute of <message> is the sender, the to attribute is the receiver, and the content of the <body> sub-element is the chat information.

<Message from = "xxg1 @ host" to = "xxg2 @ host" type = "chat"> <body> Hello </body> </message>

<Presence>:

It can be used to indicate the user's status. For example, if the user's status changes to "Do not disturb" ("Do not disturb"), it will be sent to the server:

<presence from="xxg@host">    <status>Do not disturb</status>    <priority>0</priority>    <show>dnd</show></presence>
<Iq>:

Iq is Info/Query. It adopts the "request-response" mechanism, similar to the HTTP mechanism. In the following example, the client obtains the contact through the <iq> request, and the XMPP server returns the result:

Client requests to get contacts:

<iq from='xxg@host' id='bv1bs71f' type='get'>    <query xmlns='jabber:iq:roster'/></iq>
Server result returned:

<iq to='xxg@host' id='bv1bs71f' type='result'>    <query xmlns='jabber:iq:roster'>        <item jid='xxg2@host'/>        <item jid='xxg3@host'/>    </query></iq>

Build an XMPP Server:

Before implementing Web browser chat, you must first build an XMPP server. For example, Openfire, Tigase, and Ejabberd are common XMPP servers. Openfire and Tigase are implemented based on Java, while Ejabberd is implemented by Erlang. Although the implementation languages are different, they all follow the XMPP protocol. Therefore, use any XMPP server.

The following uses Openfire and Tigase as examples.

Openfire is easy to build automatically. For more information about how to build Tigase, see my another blog post: Linux XMPP server Tigase (Spark client test ).

The XMPP server usually implements BOSH extension. The following is the default bosh url of Openfire and Tigase:

Openfire: http: // host: 7070/http-bind
Tigase: http: // host: 5280

When using Strophe. js, you must use the corresponding HTTP address to connect to the XMPP server.

If you use Opnefire, you also need to configure it in the management background:


Strophe. js:

Download: http://strophe.im/strophejs/

Implement Web private chat:

Private Chat is relatively simple. The Chat information is transmitted and exchanged through the <message> introduced above. For example, if you receive a chat message from someone else, that is, you receive a <message> element and send a chat message to someone else, that is, you send a <message> element.

HTML:

<! DOCTYPE html> JavaScript (test. js ):

// XMPP server BOSH address var BOSH_SERVICE = 'HTTP: // host: 100'; // XMPP connection var connection = null; // whether the current status is connected to var connected = false; // currently logged on JIDvar jid = ""; // function onConnect (status) {console. log (status) if (status = Strophe. status. CONNFAIL) {alert ("connection failed! ");} Else if (status = Strophe. Status. AUTHFAIL) {alert (" Logon Failed! ");} Else if (status = Strophe. Status. DISCONNECTED) {alert (" DISCONNECTED! "); Connected = false;} else if (status = Strophe. Status. CONNECTED) {alert (" connection successful, you can start chatting! "); Connected = true; // when the <message> section is received, call the onMessage callback function connection. addHandler (onMessage, null, 'message', null, null); // you must first send a <presence> to the server (initial presence) connection. send ($ pres (). tree () ;}/// receives <message> function onMessage (msg) {// parses the from and type attributes of <message>, and the body sub-element var from = msg. getAttribute ('from'); var type = msg. getAttribute ('type'); var elems = msg. getElementsByTagName ('body'); if (t Ype = "chat" & elems. length> 0) {var body = elems [0]; $ ("# msg "). append (from + ": <br>" + Strophe. getText (body) + "<br>")} return true ;}$ (document ). ready (function () {// use BOSH to connect to the XMPP server $ ('# btn-login '). click (function () {if (! Connected) {connection = new Strophe. connection (BOSH_SERVICE); connection. connect ($ ("# input-jid "). val (), $ ("# input-pwd "). val (), onConnect); jid = $ ("# input-jid "). val () ;}}); // send a message $ ("# btn-send "). click (function () {if (connected) {if ($ ("# input-contacts "). val () = '') {alert (" Enter the contact! "); Return;} // create a <message> element and send var msg = $ msg ({to: $ (" # input-contacts "). val (), from: jid, type: 'chat '}). c ("body", null, $ ("# input-msg "). val (); connection. send (msg. tree (); $ ("# msg "). append (jid + ": <br>" + $ ("# input-msg "). val () + "<br>"); $ ("# input-msg "). val ('');} else {alert (" Please log on first! ");}});});
Modify BOSH_SERVICE in JavaScript code, open the HTML file in a browser, and chat after Logon:


Implement Web chat:

XMPP group Chat is implemented through the MUC (Multi-User Chat) Extension of XMPP protocol.

Openfire supports MUC by default, but the Tigase server does not support MUC by default. You need to add the following configuration items in bold in the init. properties file:

Config-type = -- gen-config-def
-- Admins = admin @ host
-- Virt-hosts = host
-- Debug = server
-- User-db = mysql
-- User-db-uri = jdbc: mysql: // localhost: 3306/tigasedb? User = root & password = xxx
-- Comp-name-1 = muc
-- Comp-class-1 = tigase. muc. MUCComponent
-- External = muc.devel.tigase.org: muc-pass: connect: 5270: devel.tigase.org: accept

Create a room:

Creating a room can actually be written in the code, but this article uses XMPP client Spark or other tools for convenience.

First, use Spark to log on to a user at will. It is the procedure for Spark to create a room:



If Tigase is used, the created room is locked by default. Other users cannot access the room and need to unlock the room. After Spark enters the room, click the Settings button below, and then directly update the room without changing any settings (although no configuration is modified, but an update will send a <iq> to the server, this <iq> unlocked the room, refer to the http://xmpp.org/extensions/xep-0045.html#createroom-instant ):


In addition, if you use Openfire, you can directly use the management backend to create:


Join room:

After the room is created, there will be the corresponding room JID:


To join a room, you can send a <presence> message. (In fact, if the following <presence> parameter does not exist in the room, the room is created, but the created room is locked by default, you also need to send an <iq> unlock message, so this article will directly use Spark to create a room ):

<presence from='xxg@host' to='xxgroom@muc.host/xxg'>    <x xmlns='http://jabber.org/protocol/muc'/></presence>
Property to = 'xxgroom @ muc. host/xxg ', the xxgroom@muc.host represents the room JID, And the xxg represents the nickname in the room.

Chat:

Like private chat, group chat is also implemented through <message>. The difference is the type attribute of <message>. Private chat is "chat", while group chat is "groupchat". In addition, the to attribute is the JID of the room, so that a chat message will be sent to everyone in the room.

<Message from = 'xxg @ host' to = 'myroom @ muc. host' type = 'groupchat '> <body> Hello everyone! </Body> </message>
Implementation:

HTML:

<! DOCTYPE html> JavaScript (test2.js ):

// XMPP server BOSH address var BOSH_SERVICE = 'HTTP: // host: 100'; // room JIDvar ROOM_JID = 'xxgroom @ muc. host '; // XMPP connection var connection = null; // whether the current status is connected to var connected = false; // the currently logged on JIDvar jid = ""; // function onConnect (status) {if (status = Strophe. status. CONNFAIL) {alert ("connection failed! ");} Else if (status = Strophe. Status. AUTHFAIL) {alert (" Logon Failed! ");} Else if (status = Strophe. Status. DISCONNECTED) {alert (" DISCONNECTED! "); Connected = false;} else if (status = Strophe. Status. CONNECTED) {alert (" connection successful, you can start chatting! "); Connected = true; // when the <message> section is received, call the onMessage callback function connection. addHandler (onMessage, null, 'message', null, null); // you must first send a <presence> to the server (initial presence) connection. send ($ pres (). tree (); // sends the <presence> element to join the room connection. send ($ pres ({from: jid, to: ROOM_JID + "/" + jid. substring (0, jid. indexOf ("@"))}). c ('x', {xmlns: 'http: // jabber.org/protocol/muc '}). tree () ;}// receives the <message> function onMessage (Msg) {console. log (msg); // parse the from and type attributes of <message> and the body sub-element var from = msg. getAttribute ('from'); var type = msg. getAttribute ('type'); var elems = msg. getElementsByTagName ('body'); if (type = "groupchat" & elems. length> 0) {var body = elems [0]; $ ("# msg "). append (from. substring (from. indexOf ('/') + 1) + ": <br>" + Strophe. getText (body) + "<br>")} return true ;}$ (document ). ready (function () {// use BOSH Connect to the XMPP server $ ('# btn-login'). click (function () {if (! Connected) {connection = new Strophe. connection (BOSH_SERVICE); connection. connect ($ ("# input-jid "). val (), $ ("# input-pwd "). val (), onConnect); jid = $ ("# input-jid "). val () ;}}); // send a message $ ("# btn-send "). click (function () {if (connected) {// create a <message> element and send var msg = $ msg ({to: ROOM_JID, from: jid, type: 'groupchat '}). c ("body", null, $ ("# input-msg "). val (); connection. send (msg. tree (); $ ("# input-msg "). val ('');} Else {alert ("Please log on first! ");}});});

After creating a room, modify BOSH_SERVICE and ROOM_JID In the JavaScript code, open the HTML file in a browser, and then chat in the group:


In addition, Strophe. js has a specialized MUC plug-in. If you are interested, you can study it by yourself: https://github.com/strophe/strophejs-plugins/tree/master/muc.



Author: Cross brother reprint please indicate the source: http://blog.csdn.net/xiao__gui/article/details/42642573




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.