topicserver.java

来自「21天学通J2EE的例子4」· Java 代码 · 共 70 行

JAVA
70
字号
import javax.naming.*;
import javax.jms.*;

public class TopicServer implements MessageListener
{
	private String JMSFactory = "jms/TopicConnectionFactory";
	private String JMSTopic = "jms/Topic";

	private ChatDisplay display;

	private Connection connection;
    private Session session;
    private MessageProducer publisher;
    private MessageConsumer subscriber;

	public TopicServer(ChatDisplay display, String JMSTopic) throws NamingException, JMSException {
		this.display = display;
		if (JMSTopic != null)
			this.JMSTopic = JMSTopic;

        Context context = new InitialContext();
        ConnectionFactory factory = (ConnectionFactory)context.lookup(JMSFactory);
        connection = factory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination topic = (Topic)context.lookup(this.JMSTopic);

		publisher = session.createProducer(topic);

		subscriber = session.createConsumer(topic);
		subscriber.setMessageListener(this);
      	connection.start();
	}

	public void send (String from, String message) throws JMSException {
        TextMessage text = session.createTextMessage();
        text.setStringProperty ("From", from);
        text.setText(message);
        publisher.send(text);
	}

    public void onMessage(Message message) {
        try {
            if (message instanceof TextMessage) {
                TextMessage text = (TextMessage) message;
            	String from = message.getStringProperty("From");
            	if (from == null)
            		from = "Unknown";
                display.addMessage(from, text.getText());
            }
            else
            	System.out.println("Unknown message type: "+message);
        }
        catch(JMSException ex) {
			 ex.printStackTrace();
             display.error("OnMessage Exception",ex.toString());
        }
    }

	public void shutdown () {
		try {
		    publisher.close();
            subscriber.close();
			session.close();
			connection.close();
        }
        catch(JMSException ex) {}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?