1 24 package chat; 25 26 import javax.jms.*; 27 import javax.naming.*; 28 import java.io.*; 29 import java.io.InputStreamReader ; 30 import java.util.Properties ; 31 32 40 public class SimpleChat implements javax.jms.MessageListener { 41 42 private ConnectionFactory conFactory; 43 private Session pubSession; 44 private Session subSession; 45 private MessageProducer publisher; 46 private MessageConsumer subscriber; 47 private Connection connection; 48 private String userName; 49 50 51 public SimpleChat(String topicName, String username) throws Exception { 52 53 InitialContext jndi = null; 54 55 try { 56 jndi = new InitialContext(); 57 } catch( Exception e) { 58 System.out.println( e.toString() ); 59 System.exit(2); 60 } 61 62 conFactory = (ConnectionFactory)jndi.lookup("factoryChat"); 64 65 connection = conFactory.createConnection(); 67 68 pubSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 70 subSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 71 72 Topic chatTopic = (Topic)jndi.lookup(topicName); 74 75 publisher = pubSession.createProducer(chatTopic); 77 subscriber = subSession.createConsumer(chatTopic); 78 79 subscriber.setMessageListener(this); 81 82 userName = username; 84 connection.start( ); 85 86 } 87 88 89 public void onMessage(Message message) { 90 try { 91 TextMessage textMessage = (TextMessage) message; 92 String text = textMessage.getText( ); 93 System.out.println(textMessage.getStringProperty("User") + ": " + text); 94 } catch (JMSException jmse) { 95 jmse.printStackTrace( ); 96 } 97 } 98 99 100 protected void writeMessage(String text) throws JMSException { 101 TextMessage message = pubSession.createTextMessage( ); 102 message.setText(text); 103 message.setStringProperty("User", userName); 104 publisher.send(message); 105 } 106 107 108 public void close( ) throws JMSException { 109 connection.close( ); 110 } 111 112 113 public static void main(String [] args){ 114 115 SimpleChat chat = null; 116 String user = null; 117 118 try { 119 user = args[0]; 120 } catch(Exception e) { 121 user = "No name"; 122 } 123 124 try { 125 126 chat = new SimpleChat("topicChat", user); 127 128 BufferedReader commandLine = new 130 java.io.BufferedReader (new InputStreamReader (System.in)); 131 132 134 System.out.println("User: " + user + " connected !"); 135 System.out.println("Type your phrases and press 'ENTER' ..."); 136 System.out.println("Type 'exit' or 'quit' to abandon the chat."); 137 138 while(true) { 139 String s = commandLine.readLine( ); 140 if ( s.equalsIgnoreCase("exit") || s.equalsIgnoreCase("quit") ) { 141 chat.close( ); System.exit(0); } else 144 chat.writeMessage(s); 145 } 146 147 } catch(Exception e) { 148 System.out.println( e.toString()); 149 } 150 } 151 } 152 | Popular Tags |