Strophe.js Connect XMPP server OpenFire, tigase implement web private chat, group chat (MUC)

Source: Internet
Author: User
Tags gettext

XMPP (extensible Messaging and Presence Protocol) is a network Instant Messaging protocol, which is based on XML and is widely used in instant messaging software, online game chat, web chat and web message push, Scenarios such as message push for mobile devices, such as Google's Gtalk, the League of Legends LOL game chat module.

Because JavaScript on a Web browser cannot handle the TCP protocol directly, the XMPP server typically provides the Bosh (Bidirectional-streams over synchronous HTTP) interface. The HTTP long rotation (long-polling) enables real-time web browser chat. Strophe.js is a tool library that connects Web browsers and XMPP servers via Bosh.

Introduction to XMPP protocol:

Between the XMPP server and the client, it communicates through an XML section (XML Stanza). There are three kinds of very important XML stanza types:<message>, <presence>, <iq>.

<message>:

The sending and receiving of chat messages is done through the message section. For example [email protected] Send a message "Hello" to [e-mail Protected],[email protected] The client will send the following XML to the XMPP server, the server is then pushed to the [email protected] Client. Where the From property of <message> is the sender, the to attribute is the content of the recipient,<body> child element is the chat message.

<message from= "[email protected]" to= "[email protected]" type= "chat" >    <body> Hello </body></ Message>

<presence>:

Can be used to indicate the state of a user, such as a change in user status to "Do Not Disturb" ("Don't Disturb"), which is sent to the server:

<presence from= "[email protected]" >    <status>do not disturb</status>    <priority>0 </priority>    <show>dnd</show></presence>

<iq>:

IQ is info/query, using the "request-response" mechanism, similar to the HTTP mechanism. The following example is where the client obtains a contact through <iq>, and the XMPP server returns the result:

Client requests to get contacts:

<iq from= ' [email protected] ' id= ' bv1bs71f ' type= ' get ' >    <query xmlns= ' Jabber:iq:roster '/></iq>

Server results returned:

<iq to= ' [email protected] ' id= ' bv1bs71f ' type= ' result ' >    <query xmlns= ' jabber:iq:roster ' >        < Item jid= ' [email protected] '/>        <item jid= ' [email protected] '/>    </query></iq>

To build an XMPP server:

Before you implement a Web browser chat, you first need to build an XMPP server. For example, OpenFire, Tigase, and Ejabberd are common XMPP servers. Where OpenFire and Tigase are based on Java implementations, Ejabberd is the Erlang implementation. Although the languages implemented are different, they all follow the XMPP protocol, so you can use either of these XMPP servers.

Let's take OpenFire and Tigase as an example.

OpenFire can be automated to build very convenient, this article no longer introduced. Tigase's Build can refer to my other blog post: Linux builds XMPP server tigase (Spark Client test).

XMPP servers typically implement Bosh extensions, the following are the Bosh default URLs for OpenFire and tigase:

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

When using strophe.js, you need to use the corresponding HTTP address to connect to the XMPP server.

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

Strophe.js:

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

To implement web private chat:

Private chat is relatively simple, chat information through the above-mentioned <message> to carry out exchange. For example, to receive a chat message from someone else, that is, to receive a <message> element, send someone a chat message, that is, sending a <message> element.

Html:

<! DOCTYPE html>

JavaScript (test.js):

XMPP server BOSH address var bosh_service = ' http://host:5280 ';//XMPP connection var connection = null;//The current state is connected to var connected = false;//When Pre-Login Jidvar Jid = "";//Connection Status Change Event function OnConnect (status) {Console.log (status) if (status = Strophe.Status.CONNFA IL) {alert ("Connection failed!    "); } else if (status = = Strophe.Status.AUTHFAIL) {alert ("Login failed!    "); } else if (status = = Strophe.Status.DISCONNECTED) {alert ("Connection broken!        ");    connected = false; } else if (status = = Strophe.Status.CONNECTED) {alert ("The connection is successful, you can start chatting!")        ");                connected = true;                When receiving the <message> section, call the OnMessage callback function Connection.addhandler (onMessage, NULL, ' message ', NULL, NULL, NULL);    First, send a <presence> to the server (initial presence) Connection.send ($pres (). tree ()); }}//received <message>function onMessage (msg) {//parse out <message> from, type attribute, and body sub-element var from = Msg.geta    Ttribute (' from ');    var type = Msg.getattribute (' type '); var elems = Msg.geteLementsbytagname (' body ');        if (type = = "Chat" && elems.length > 0) {var body = elems[0]; $ ("#msg"). Append (from + ":<br>" + strophe.gettext (body) + "<br>")} return true;            $ (document). Ready (function () {//* Connect XMPP server through Bosh $ (' #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 Message $ ("#btn-send"). Click (function () {if (connected) {if ("#input-contacts"). val () = = ") { Alert ("Please enter a 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 login first!        "); }    });});

Modify the Bosh_service in the JavaScript code, open the HTML file with your browser, and chat after you log in:

To implement Web group chat:

XMPP group Chat is implemented through the MUC (multi-user Chat) extension of the XMPP protocol.

OpenFire supports MUC by default, but the Tigase server does not support MUC by default, and you need to include the following bold-section configuration entries in the Init.properties file:

Config-type=--gen-config-def
[Email protected]
--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 code, but this article is created using XMPP client spark or other tools for convenience.

Start by using spark to sign in to a user, the steps to create a room with spark:

If you are using Tigase, the default created room is locked, other users cannot enter, and the room needs to be unlocked. When Spark enters the room, click the Settings button below, and then update to unlock the room without changing any settings (although no configuration is modified, but the update sends a <iq> to the server, this <iq> unlocks the room, reference HTTP// Xmpp.org/extensions/xep-0045.html#createroom-instant):

Also, if you use OpenFire, you can create them directly using the admin background:

Join the room:

After the room has been created, there is a corresponding room Jid:

To join a room can be implemented by sending a <presence> (in fact, if the room does not exist below this <presence> will also create a room, but the created room by default lock, also need to send a <iq> unlock, So this article creates a room directly with spark):

<presence from= ' [email protected] ' to= ' [email protected]/xxg ' >    <x xmlns= ' http://jabber.org/protocol/ Muc '/></presence>

Attribute to= ' [email protected]/xxg ', [email protected] indicates that the room JID,XXG represents the nickname in the room.

Chat:

and private chat, group chat is also achieved through <message>, the difference is the Type property of <message>, private chat is "chat", and group chat is "Groupchat", in addition, to the property is the room Jid, Such a chat message will be sent to everyone in the room.

<message from= ' [email protected] ' to= ' [email protected] ' type= ' groupchat ' >  <body> Hello everyone! </body></message>

Realize:

Html:

<! DOCTYPE html>

JavaScript (test2.js):

XMPP server BOSH address var bosh_service = ' http://host:5280 ';//room Jidvar Room_jid = ' [email protected] ';//XMPP connection var Connection = null;//Whether the current state is connected to var connected = false;//The currently logged on Jidvar Jid = "";//Event function OnConnect (status) Change of connection status {if (Status = = Strophe.Status.CONNFAIL) {Alert ("Connection failed!    "); } else if (status = = Strophe.Status.AUTHFAIL) {alert ("Login failed!    "); } else if (status = = Strophe.Status.DISCONNECTED) {alert ("Connection broken!        ");    connected = false; } else if (status = = Strophe.Status.CONNECTED) {alert ("The connection is successful, you can start chatting!")        ");                connected = true;                When receiving the <message> section, call the OnMessage callback function Connection.addhandler (onMessage, NULL, ' message ', NULL, NULL, NULL);        First, send a <presence> to the server (initial presence) Connection.send ($pres (). tree ()); Send <presence> elements, add room Connection.send ($pres ({from:jid, To:room_jid + "/" + jid.subs Tring (0,jid.indexof ("@"))}). C (' x ', {xmlns: ' HTtp://jabber.org/protocol/muc '}). tree ());    }}//received <message>function onMessage (msg) {Console.log (msg);    Parse out the From, type attribute 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>")} RET Urn true;}            $ (document). Ready (function () {//* Connect XMPP server through Bosh $ (' #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 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 login first!        "); }    });});

Create a good room, modify bosh_service and Room_jid in the JavaScript code, open the HTML file with a browser, log in and then group chat:

In addition, Strophe.js also has a specialized MUC plug-in, interested students can study under their own: HTTPS://GITHUB.COM/STROPHE/STROPHEJS-PLUGINS/TREE/MASTER/MUC.

Strophe.js Connect XMPP server OpenFire, tigase implement web private chat, group chat (MUC)

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.