Message Types
The TextMessage contains a string. If you want to communicate with non-JMS systems, text messages are often the right choice (with XML in a BytesMessage being the main alternative), as they are supported almost everywhere and are not JMS- or Java-specific.
// Create message
Session session = ...;
TextMessage msg = session.createTextMessage("some text here");
// Read message
String text = msg.getText();
The MapMessage allows you to store name/value pairs. The names are always strings, and the values can be either Java primitives, strings or byte arrays. The pairs do not have an order.
// Create message
Session session = ...;
MapMessage msg = session.createMapMessage();
msg.setString("title", "Thriller");
msg.setInt("releaseYear", 1982);
msg.setDouble("millionsSold", 110.3);
// Read message
int releaseYear = msg.getInt("releaseYear"); // can be read in any order
String title = msg.getString("title");
double millionsSold = msg.getDouble("millionsSold");
The StreamMessage allows you to store a stream of Java number and string values. When received, the values must be read in exactly the same order as they have been written.
// Create message
Session session = ...;
StreamMessage msg = session.createStreamMessage();
msg.writeString("Thriller");
msg.writeInt(1982);
msg.writeDouble(110.3);
// Read message
String title = msg.readString(); // must be read in the same order as written
int releaseYear = msg.readInt();
double millionsSold = msg.readDouble();
The ObjectMessage allows you to store any serializable Java object.
// Create message
Session session = ...;
Date obj = new Date(); // the object to send
ObjectMessage msg = session.createObjectMessage(obj);
// Read message
Date d = (Date) msg.getObject();
The BytesMessage is the raw equivalent of the StreamMessage. It allows you to write the bytes directly in a server-specific format. Its mostly useful for transmitting byte arrays.
// Create message
Session session = ...;
byte[] blob = ...; // any binary data
BytesMessage msg = session.createBytesMessage();
msg.writeBytes(blob);
// Read message
byte[] newBlob = new byte[(int) msg.getBodyLength()];
msg.readBytes();
It is also possible to create untyped messages without content (they may still contain header data and properties). This may be useful, for example, if the message should only trigger an action and does not need any additional data.
Session session = ...;
Message msg = session.createMessage();