
examples.jms.stomp.readme.html Maven / Gradle / Ivy
The newest version!
HornetQ Stomp Example
Stomp Example
This example shows you how to configure HornetQ to send and receive Stomp messages.
The example will start a HornetQ server configured with Stomp and JMS.
The client will open a socket to send one Stomp message (using TCP directly).
The client will then consume a message from a JMS Queue and check it is the message sent with Stomp.
Example step-by-step
To run the example, simply type ./build.sh
(or build.bat
on windows) from this directory
- We create a TCP socket to connect to the Stomp port
Socket socket = new Socket("localhost", 61613);
- We send a CONNECT frame to connect to the server
String connectFrame = "CONNECT\n" +
"login: guest\n" +
"passcode: guest\n" +
"request-id: 1\n" +
"\n" +
Stomp.NULL;
sendFrame(socket, connectFrame);
- We send a SEND frame (a Stomp message) to the destination
jms.queue.exampleQueue
(which corresponds to the HornetQ address for the JMS Queue exampleQueue
) with a text body
String text = "Hello, world from Stomp!";
String message = "SEND\n" +
"destination: jms.queue.exampleQueue\n" +
"\n" +
text +
Stomp.NULL;
sendFrame(socket, message);
System.out.println("Sent Stomp message: " + text);
- We send a DISCONNECT frame to disconnect from the server
String disconnectFrame = "DISCONNECT\n" +
"\n" +
Stomp.NULL;
sendFrame(socket, disconnectFrame);
- We close the TCP socket
socket.close();
- We create an initial context to perform the JNDI lookup.
initialContext = getContext(0);
- We perform a lookup on the queue and the connection factory
Queue queue = (Queue)initialContext.lookup("/queue/exampleQueue");
ConnectionFactory cf = (ConnectionFactory)initialContext.lookup("/ConnectionFactory");
- We create a JMS Connection, Session and a MessageConsumer on the queue
connection = cf.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queue);
- We start the connection
connection.start();
- We receive the message. Stomp messages are mapped to JMS TextMessage.
TextMessage messageReceived = (TextMessage)consumer.receive(5000);
System.out.println("Received JMS message: " + messageReceived.getText());
- And finally, always remember to close your JMS connections and resources after use, in a
finally
block. Closing a JMS connection will automatically close all of its sessions, consumers, producer and browser objects
finally
{
if (initialContext != null)
{
initialContext.close();
}
if (connection != null)
{
connection.close();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy