- //文本消息
- TextMessage textMessage = session.createTextMessage("文本消息");
- producer.send(textMessage);
- //键值对消息
- MapMessage mapMessage = session.createMapMessage();
- mapMessage.setLong("age", new Long(32));
- mapMessage.setDouble("sarray", new Double(5867.15));
- mapMessage.setString("username", "键值对消息");
- producer.send(mapMessage);
- //流消息
- StreamMessage streamMessage = session.createStreamMessage();
- streamMessage.writeString("streamMessage流消息");
- streamMessage.writeLong(55);
- producer.send(streamMessage);
- //字节消息
- String s = "BytesMessage字节消息";
- BytesMessage bytesMessage = session.createBytesMessage();
- bytesMessage.writeBytes(s.getBytes());
- producer.send(bytesMessage);
- //对象消息
- User user = new User("cjm", "对象消息"); //User对象必须实现Serializable接口
- ObjectMessage objectMessage = session.createObjectMessage();
- objectMessage.setObject(user);
- producer.send(objectMessage);
- if(m instanceof TextMessage){ //接收文本消息
- TextMessage message = (TextMessage)m;
- System.out.println(message.getText());
- }else if(m instanceof MapMessage){ //接收键值对消息
- MapMessage message = (MapMessage)m;
- System.out.println(message.getLong("age"));
- System.out.println(message.getDouble("sarray"));
- System.out.println(message.getString("username"));
- }else if(m instanceof StreamMessage){ //接收流消息
- StreamMessage message = (StreamMessage)m;
- System.out.println(message.readString());
- System.out.println(message.readLong());
- }else if(m instanceof BytesMessage){ //接收字节消息
- byte[] b = new byte[1024];
- int len = -1;
- BytesMessage message = (BytesMessage)m;
- while((len=message.readBytes(b))!=-1){
- System.out.println(new String(b, 0, len));
- }
- }else if(m instanceof ObjectMessage){ //接收对象消息
- ObjectMessage message = (ObjectMessage)m;
- User user = (User)message.getObject();
- System.out.println(user.getUsername() + " _ " + user.getPassword());
- }else{
- System.out.println(m);
- }