1 28 29 package jms; 33 34 import javax.jms.Connection; 35 import javax.jms.ConnectionFactory; 36 import javax.jms.Message; 37 import javax.jms.MessageConsumer; 38 import javax.jms.MessageListener; 39 import javax.jms.ObjectMessage; 40 import javax.jms.Session; 41 import javax.jms.TextMessage; 42 import javax.jms.Topic; 43 import javax.naming.Context; 44 import javax.naming.InitialContext; 45 import javax.naming.NamingException; 46 47 50 public class MsgReceptor { 51 52 private static Context ictx = null; 53 54 private static ConnectionFactory cf = null; 55 56 private static Topic topic = null; 57 58 private static String conFactName = "JCF"; 60 61 private static String topicName = "sampleTopic"; 63 64 public static void main(String[] arg) { 65 66 try { 68 ictx = new InitialContext(); 69 cf = (ConnectionFactory) ictx.lookup(conFactName); 71 72 System.out.println("JMS client: cf = " + cf.toString()); 73 74 topic = (Topic) ictx.lookup(topicName); 76 System.out.println("JMS Topic topic = " + topic.toString()); 77 } catch (NamingException e) { 78 e.printStackTrace(); 79 System.exit(2); 80 } 81 82 try { 83 Connection tc = cf.createConnection(); 84 System.out.println("JMS client: tc = " + tc.toString()); 85 Session session = tc.createSession(false, Session.AUTO_ACKNOWLEDGE); 86 MessageConsumer mc = session.createConsumer(topic); 87 88 MyListenerSimple listener = new MyListenerSimple(); 89 mc.setMessageListener(listener); 90 91 System.out.println("JMS client: Waiting for messages ..."); 92 tc.start(); 93 94 System.in.read(); 95 96 session.close(); 97 tc.close(); 98 } catch (Exception e) { 99 System.out.println("Exception in message reception operations"); 100 e.printStackTrace(); 101 } 102 103 } 104 } 105 106 class MyListenerSimple implements MessageListener { 107 108 MyListenerSimple() { 109 } 110 111 public void onMessage(Message msg) { 112 try { 113 if (msg == null) { 114 System.out.println("Message: message null "); 115 } else { 116 if (msg instanceof ObjectMessage) { 117 String m = (String) ((ObjectMessage) msg).getObject(); 118 System.out.println("JMS client: received message ======> " + m); 119 } else if (msg instanceof TextMessage) { 120 String m = ((TextMessage) msg).getText(); 121 System.out.println("JMS client: received message ======> " + m); 122 } 123 } 124 } catch (Exception exc) { 125 System.out.println("Exception caught :" + exc); 126 exc.printStackTrace(); 127 } 128 } 129 } | Popular Tags |