Beruflich Dokumente
Kultur Dokumente
What is STOMP?
STOMP is a simple text-orientated messaging protocol. It defines an
interoperable wire format so that any of the available STOMP clients can
communicate with any STOMP message broker to provide easy and
widespread messaging interoperability among languages and platforms (the
STOMP web site has a list of STOMP client and server implementations.
Protocol Support
This library supports multiple version of STOMP protocols:
STOMP 1.0
STOMP 1.1 (including heart-beating)
Server Requirements
This library is not a pure STOMP client. It is aimed to run on the WebSockets protocol which is
not TCP. Basically, the WebSocket protocol requires a handshake between the browser's client and
the server to ensure the browser's "same-origin" security model remains in effect.
This means that this library can not connect to regular STOMP brokers since they would not
understand the handshake initiated by the WebSocket which is not part of the STOMP protocol
and would likely reject the connection.
There are ongoing works to add WebSocket support to STOMP broker so that they will accept
STOMP connections over the WebSocket protocol.
HornetQ
HornetQ is the Open Source messaging system developed by Red Hat and JBoss.
To start HornetQ with support for STOMP Over WebSocket, download the latest version and run
the following steps:
$cdhornetqx.y.z/examples/jms/stompwebsockets
$mvncleaninstall
...
INFO:HQ221020:StartedNettyAcceptorversion3.6.2.Finalc0d783clocalhost:61614forSTOMP_WSprotocol
Apr15,20131:15:33PMorg.hornetq.core.server.impl.HornetQServerImpl$SharedStoreLiveActivationrun
INFO:HQ221007:Serverisnowlive
Apr15,20131:15:33PMorg.hornetq.core.server.impl.HornetQServerImplstart
INFO:HQ221001:HornetQServerversion2.3.0.CR2(black'n'yellow2,123)[c9e29e45a5bd11e2976ab3fef7ce
HornetQ is now started and listens to STOMP over WebSocket on the port 61614.
It accepts WebSocket connections from the URL ws://localhost:61614/stomp
To configure and run HornetQ with STOMP Over WebSocket enabled, follow the instructions.
ActiveMQ
ActiveMQ is the Open Source messaging system developed by Apache. Starting with 5.4
snapshots, ActiveMQ supports STOMP Over WebSocket.
To configure and run ActiveMQ with STOMP Over WebSocket enabled, follow the instructions.
ActiveMQ Apollo
ActiveMQ Apollo is the next generation of ActiveMQ broker. From the start, Apollo supports
STOMP Over WebSocket.
To configure and run Apollo with STOMP Over WebSocket enabled, follow the instructions.
RabbitMQ
RabbitMQ is Open Source messaging system sponsored by VMware.
To configure and run RabbitMQ with STOMP Over WebSocket enabled, follow the instructions
to install the Web-Stomp plugin.
STOMP API
STOMP Frame
STOMP Over WebSocket provides a straightforward mapping from a STOMP frame to a
JavaScript object.
Frame Object
Property
Type
Notes
command
String
headers
JavaScript object
body
String
The commandand headersproperties will always be defined but the headerscan be empty if the
frame has no headers. The bodycan be nullif the frame does not have a body.
Use Stomp.client(url)to use regular WebSockets or use Stomp.over(ws)if you required another
type of WebSocket.
Apart from this initialization, the STOMP API remains the same in both cases.
In a node.js application
The library can also be used in node.js application by using the stompjs npm package.
$npminstallstompjs
To connect to a STOMP broker over a Web Socket, use instead the Stomp.overWS(url)method:
varclient=Stomp.overWS('ws://localhost:61614/stomp');
Apart from this initialization, the STOMP API remains the same whether it is running in a Web
browser or in node.js application.
Behind the scene, the client will open a connection using a WebSocket and send a CONNECT
frame.
The connection is done asynchronously: you have no guarantee to be effectively connected when
the call to connectreturns. To be notified of the connection, you need to pass a connect_callback
function to the connect()method:
varconnect_callback=function(){
//calledbackaftertheclientisconnectedandauthenticatedtotheSTOMPserver
};
But what happens if the connection fails? the connect()method accepts an optional
error_callbackargument which will be called if the client is not able to connect to the server.
The callback will be called with a single argument, an error object corresponding to STOMP
ERROR frame:
varerror_callback=function(error){
//displaytheerror'smessageheader:
alert(error.headers.message);
};
The connect()method accepts different number of arguments to provide a simple API to use in
most cases:
client.connect(login,passcode,connectCallback);
client.connect(login,passcode,connectCallback,errorCallback);
client.connect(login,passcode,connectCallback,errorCallback,host);
passcode:'mypasscode',
//additionalheader
'clientid':'myclientid'
};
client.connect(headers,connectCallback);
To disconnect a client from the server, you can call its disconnect()method. The disconnection
is asynchronous: to be notified when the disconnection is effective, the disconnectmethod takes
an optional callbackargument.
client.disconnect(function(){
alert("Seeyounexttime!");
};
Heart-beating
If the STOMP broker accepts STOMP 1.1 frames, heart-beating is enabled by default.
The clientobject has a heartbeatfield which can be used to configure heart-beating by
changing its incomingand outgoinginteger fields (default value for both is 10000ms):
client.heartbeat.outgoing=20000;//clientwillsendheartbeatsevery20000ms
client.heartbeat.incoming=0;//clientdoesnotwanttoreceiveheartbeats
//fromtheserver
Send messages
When the client is connected to the server, it can send STOMP messages using the send()
method. The method takes a mandatory destinationargument corresponding to the STOMP
destination. It also takes two optional arguments: headers, a JavaScript object containing
additional message headers and body, a String object.
client.send("/queue/test",{priority:9},"Hello,STOMP");
The client will send a STOMP SEND frame to /queue/testdestination with a header priorityset
to 9and a body Hello,STOMP.
If you want to send a message with a body, you must also pass the headers
argument. If you have no headers to pass, use an empty JavaScript literal {}:
client.send(destination,{},body);
The subscribe()methods returns a JavaScript obect with 1 attribute, id, that correspond to the
client subscription ID and one method unsubscribe()that can be used later on to unsubscribe
the client from this destination.
By default, the library will generate an unique ID if there is none provided in the headers. To
use your own ID, pass it using the headersargument:
varmysubid='...';
varsubscription=client.subscribe(destination,callback,{id:mysubid});
The client will send a STOMP SUBSCRIBE frame to the server and register the callback. Every
time the server send a message to the client, the client will in turn call the callback with a
STOMP Frame object corresponding to the message:
callback=function(message){
//calledwhentheclientreceivesaSTOMPmessagefromtheserver
if(message.body){
alert("gotmessagewithbody"+message.body)
}else{
alert("gotemptymessage");
}
});
The client specifies that it will handle the message acknowledgement and is interested to receive
only messages matching the selector location='Europe'.
If you want to subscribe the client to multiple destinations, you can use the same
callback to receive all the messages:
onmessage=function(message){
//calledeverytimetheclientreceivesamessage
}
varsub1=client.subscribe("queue/test",onmessage);
varsub2=client.subscribe("queue/another",onmessage);
To stop receiving messages, the client can use the unsubscribe()method on the object returned
by the subscribe()method.
varsubscription=client.subscribe(...);
...
subscription.unsubscribe();
JSON support
The body of a STOMP message must be a String. If you want to send and receive JSON objects,
you can use JSON.stringify()and JSON.parse()to transform the JSON object to a String and
vice versa.
varquote={symbol:'APPL',value:195.46};
client.send("/topic/stocks",{},JSON.stringify(quote));
client.subcribe("/topic/stocks",function(message){
varquote=JSON.parse(message.body);
alert(quote.symbol+"isat"+quote.value);
};
Acknowledgment
By default, STOMP messages will be automatically acknowledged by the server before the
message is delivered to the client.
The client can chose instead to handle message acknowledgement by subscribing to a destination
and specify a ackheader set to clientor clientindividual.
In that case, the client must use the message.ack()method to inform the server that it has
acknowledge the message.
varsubscription=client.subscribe("/queue/test",
function(message){
//dosomethingwiththemessage
...
//andacknowledgeit
message.ack();
},
{ack:'client'}
);
vartx=client.begin();
message.ack({transaction:tx.id,receipt:'myreceipt'});
tx.commit();
The nack()method can also be used to inform STOMP 1.1 brokers that the client did not
consume the message. It takes the same arguments than the ack()method.
Transactions
Messages can be sent and acknowledged in a transaction.
A transaction is started by the client using its begin()method which takes an optional
transaction, a String which uniquely identifies the transaction. If no transactionis passed, the
The client can then send and/or acknowledge messages in the transaction by specifying a
transactionset with the transaction id.
//startthetransaction
vartx=client.begin();
//sendthemessageinatransaction
client.send("/queue/test",{transaction:tx.id},"messageinatransaction");
//committhetransactiontoeffectivelysendthemessage
tx.commit();
If you forget to add the transactionheader when calling send()the message will
not be part of the transaction and will be sent directly without waiting for the
completion of the transaction.
vartxid="unique_transaction_identifier";
//startthetransaction
vartx=client.begin();
//oops!sendthemessageoutsidethetransaction
client.send("/queue/test",{},"IthoughtIwasinatransaction!");
tx.abort();//Toolate!themessagehasbeensent
Debug
There are few tests in the code and it is helpful to see what is sent and received from the library
to debug application.
The client can set its debugproperty to a function with takes a Stringargument to see all the
By default, the debug messages are logged in the browser window's console.
Example
The source code contains a chat example in examples/chat/index.html
You need to start a STOMP server with support for WebSocket (using for example HornetQ).
Click on the Connectbutton to connect to the server and subscribe to the /queue/test/queue.
You can then type messages in the form at the bottom of the page to send STOMP messages to
the queue. Messages received by the client will be displayed at the top of the page.
You can also send regular STOMP messages and see them displayed in the browser. For example
using directly telneton STOMP default port:
$telnetlocalhost61613
CONNECT
login:guest
passcode:guest
^@
CONNECTED
session:1092296064
Contribute
The source code is hosted on GitHub:
gitclonegit://github.com/jmesnil/stompwebsocket.git