STOMP Over WebSocket
- 作者: 五速梦信息网
- 时间: 2026年04月04日 13:25
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.
What is the WebSocket API?
Your browser supports WebSockets.
WebSockets are "TCP for the Web".
When Google announced the availability of
WebSocket in Google Chrome,
it explained the idea behind WebSockets:
The WebSocket API enables web applications to handle bidirectional communications
with server-side process in a straightforward way. Developers have been using XMLHttpRequest
("XHR") for such purposes, but XHR makes developing web applications that communicate back
and forth to the server unnecessarily complex. XHR is basically asynchronous HTTP,
and because you need to use a tricky technique like long-hanging GET for sending data
from the server to the browser, simple tasks rapidly become complex. As opposed to XMLHttpRequest,
WebSockets provide a real bidirectional communication channel in your browser.
Once you get a WebSocket connection, you can send data from browser to server by calling
a send() method, and receive data from server to browser by an onmessage event handler.In addition to the new WebSocket API, there is also a new protocol
(the "WebSocket Protocol") that the browser uses to communicate with servers.
The protocol is not raw TCP because it needs to provide the browser's "same-origin"
security model. It's also not HTTP because WebSocket traffic differers from HTTP's
request-response model. WebSocket communications using the new WebSocket protocol
should use less bandwidth because, unlike a series of XHRs and hanging GETs,
no headers are exchanged once the single connection has been established. To use this new
API and protocol and take advantage of the simpler programming model and more
efficient network traffic, you do need a new server implementation to communicate
with.
The API is part of HTML5 and is supported (at various degree...) by most modern Web Browsers (including Google Chrome, Firefox and Safari on Mac OS X and iOS).
Protocol Support
This library supports multiple version of STOMP protocols:
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:
$ cd hornetq-x.y.z/examples/jms/stomp-websockets$ mvn clean install...
INFO: HQ221020: Started Netty Acceptor version 3.6.2.Final-c0d783c localhost:61614 for STOMP_WS protocol
Apr 15, 2013 1:15:33 PM org.hornetq.core.server.impl.HornetQServerImpl$SharedStoreLiveActivation run
INFO: HQ221007: Server is now live
Apr 15, 2013 1:15:33 PM org.hornetq.core.server.impl.HornetQServerImpl start
INFO: HQ221001: HornetQ Server version 2.3.0.CR2 (black'n'yellow2, 123) [c9e29e45-a5bd-11e2-976a-b3fef7ceb5df]
61614ws://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.
Stilts & Torquebox
Stilts is a STOMP-native
messaging framework which aims to address treating STOMP as primary
contract for messaging, and integrating around it, instead of simply
applying STOMP shims to existing services.
TorqueBox uses the Stilts project to provide its WebSockets and STOMP stack.
Download stomp.js JavaScript file
You can download stomp.js to use it in your Web applications
A minified version is also provided to be used in production.
This JavaScript file is generated from CoffeeScript files. See the Contribute section to download the source code or browse the annotated source code.
STOMP API
STOMP Frame
STOMP Over WebSocket provides a straightforward mapping from a STOMP frame to a JavaScript
object.
command"CONNECT""SEND"headersbody
commandheadersheadersbodynull
Create a STOMP client
In a Web browser with regular Web Socket
ws://
Stomp.client(url)
var url = "ws://localhost:61614/stomp";
var client = Stomp.client(url);
Stomp.client(url, protocols)['v10.stomp', 'v11.stomp]'
In the Web browser with a custom WebSocket
stomp.jsWebSocket
Stomp.over(ws)
For example, it is possible to use the implementation provided by the SockJS project which falls back to a variety of browser-specific transport protocols instead:
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>
<script>
// use SockJS implementation instead of the browser's native implementation
var ws = new SockJS(url);
var client = Stomp.over(ws);
[...]
</script>
Stomp.client(url)Stomp.over(ws)
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.
$ npm install stompjs
In the node.js app, require the module with:
var Stomp = require('stompjs');
Stomp.overTCP(host, port)
var client = Stomp.overTCP('localhost', 61613);
Stomp.overWS(url)
var client = 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.
Connection to the server
connect()loginpasscode
Behind the scene, the client will open a connection using a WebSocket and send a CONNECT frame.
connectconnect_callbackconnect()
var connect_callback = function() {
// called back after the client is connected and authenticated to the STOMP server
};
connect()error_callback
var error_callback = function(error) {
// display the error's message header:
alert(error.headers.message);
};
connect()
client.connect(login, passcode, connectCallback);
client.connect(login, passcode, connectCallback, errorCallback);
client.connect(login, passcode, connectCallback, errorCallback, host);
loginpasscodeconnectCallbackerrorCallback
connect()
client.connect(headers, connectCallback);
client.connect(headers, connectCallback, errorCallback);
headerconnectCallbackerrorCallback
loginpasscodehost
var headers = {
login: 'mylogin',
passcode: 'mypasscode',
// additional header
'client-id': 'my-client-id'
};
client.connect(headers, connectCallback);
disconnect()disconnectcallback
client.disconnect(function() {
alert("See you next time!");
};
When a client is disconnected, it can no longer send or receive messages.
Heart-beating
If the STOMP broker accepts STOMP 1.1 frames, heart-beating is enabled by default.
clientheartbeatincomingoutgoing10000
client.heartbeat.outgoing = 20000; // client will send heartbeats every 20000ms
client.heartbeat.incoming = 0; // client does not want to receive heartbeats
// from the server
window.setInterval()
Send messages
send()destinationheadersbody
client.send("/queue/test", {priority: 9}, "Hello, STOMP");
/queue/testpriority9Hello, STOMP
Subscribe and receive messages
To receive messages in the browser, the STOMP client must first subscribe to a destination.
subscribe()destinationcallbackmessageheaders
var subscription = client.subscribe("/queue/test", callback);
subscribe()idunsubscribe()
headers
var mysubid = '...';
var subscription = 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) {
// called when the client receives a STOMP message from the server
if (message.body) {
alert("got message with body " + message.body)
} else {
alert("got empty message");
}
});
subscribe()headers
var headers = {ack: 'client', 'selector': "location = 'Europe'"};
client.subscribe("/queue/test", message_callback, headers);
location = 'Europe'
unsubscribe()subscribe()
var subscription = client.subscribe(...);
...
subscription.unsubscribe();
JSON support
StringJSON.stringify()JSON.parse()
var quote = {symbol: 'APPL', value: 195.46};
client.send("/topic/stocks", {}, JSON.stringify(quote));
client.subcribe("/topic/stocks", function(message) {
var quote = JSON.parse(message.body);
alert(quote.symbol + " is at " + quote.value);
};
Acknowledgment
By default, STOMP messages will be automatically acknowledged by the server before the message is delivered to the client.
ackclientclient-individual
message.ack()
var subscription = client.subscribe("/queue/test",
function(message) {
// do something with the message
...
// and acknowledge it
message.ack();
},
{ack: 'client'}
);
ack()headersACK
var tx = client.begin();
message.ack({ transaction: tx.id, receipt: 'my-receipt' });
tx.commit();
nack()ack()
Transactions
Messages can be sent and acknowledged in a transaction.
begin()transactiontransaction
id
commit()abort()
transactionid
// start the transaction
var tx = client.begin();
// send the message in a transaction
client.send("/queue/test", {transaction: tx.id}, "message in a transaction");
// commit the transaction to effectively send the message
tx.commit();
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.
debugString
client.debug = function(str) {
// append the debug log to a #debug div somewhere in the page using JQuery:
$("#debug").append(str + "\n");
};
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).
/queue/test/
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 telnet on STOMP default port:
$ telnet localhost 61613
CONNECT
login:guest
passcode:guest ^@
CONNECTED
session:1092296064
^@ is a null (control-@ in ASCII) byte.
SEND
destination:/queue/test Hello from TCP!
^@
You should now have received this message in your browser.
Contribute
The source code is hosted on GitHub:
from :http://jmesnil.net/stomp-websocket/doc/
- 上一篇: STOMP 客户端 API 整理
- 下一篇: STM32中HAL库和标准库的区别
相关文章
-
STOMP 客户端 API 整理
STOMP 客户端 API 整理
- 互联网
- 2026年04月04日
-
StompJS使用文档总结
StompJS使用文档总结
- 互联网
- 2026年04月04日
-
stopword.dic 增加
stopword.dic 增加
- 互联网
- 2026年04月04日
-
STM32中HAL库和标准库的区别
STM32中HAL库和标准库的区别
- 互联网
- 2026年04月04日
-
STM32之VCP1VCAP2引脚的处理
STM32之VCP1VCAP2引脚的处理
- 互联网
- 2026年04月04日
-
stm32输入的功能引脚功能介绍
stm32输入的功能引脚功能介绍
- 互联网
- 2026年04月04日






