public class Chat implements MessageListener{
private TopicSession pubSession;
private TopicPublisher publisher;
private TopicConnection connection;
private String username;
public Chat(String topicFatory, String topicName, String username) throws NamingException, JMSException {
InitialContext ctx = new InitialContext();//从properties配置文件获取JDNI连接
//查找一个JMS连接工厂并创建连接
TopicConnectionFactory conFactory = (TopicConnectionFactory) ctx.lookup(topicFatory);
TopicConnection connection = conFactory.createTopicConnection();
//创建两个JMS会话对象(发布/订阅)
TopicSession pubSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
TopicSession subSession = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
//查找一个JMS主题
Topic chatTopic = (Topic) ctx.lookup(topicName);
TopicPublisher publisher = pubSession.createPublisher(chatTopic);
TopicSubscriber subscriber = subSession.createSubscriber(chatTopic, null, true);
//设置一个JMS消息侦听器
subscriber.setMessageListener(this);
//初始化Chat应用程序变量
this.connection = connection;
this.pubSession = pubSession;
this.publisher = publisher;
this.username = username;
//启动JMS连接
connection.start();
}
public void onMessage(Message message) {
TextMessage textMessage = (TextMessage) message;
try {
System.out.println(textMessage.getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
protected void writeMessage(String text) throws JMSException {
TextMessage message = pubSession.createTextMessage();
message.setText(username+": "+text);
publisher.publish(message);
}
public void close() throws JMSException {
connection.close();
}
public static void main(String[] args) {
if(args.length != 3)
System.out.println("Factory , Topoc , or username missing");
try {
Chat chat = new Chat(args[0],args[1],args[2]);
BufferedReader commandLine = new BufferedReader(new InputStreamReader(System.in));
while(true){
String s = commandLine.readLine();
if(s.equalsIgnoreCase("exit")){
chat.clone();
System.exit(0);
} else
chat.writeMessage(s);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}