⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 topicserver.java

📁 21天学通J2EE的例子4
💻 JAVA
字号:
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 + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -