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

📄 topicsend.java

📁 精通Java核心技术的随书源代码
💻 JAVA
字号:
// ==================== Program Discription ==========================
// 程序名称:示例17-4:TopicSend.java
// 程序目的:消息服务器上的主题消息建立连接并发送这个主题的消息。
// ==============================================================
package examples.jms.topic;
import java.io.*;
import java.util.*;
import javax.transaction.*;
import javax.naming.*;
import javax.jms.*;

public class TopicSend
{
  public final static String JNDI_FACTORY="weblogic.jndi.WLInitialContextFactory";
  public final static String JMS_FACTORY="weblogic.examples.jms.TopicConnectionFactory";
  public final static String TOPIC="weblogic.examples.jms.exampleTopic";

  protected TopicConnectionFactory tconFactory;
  protected TopicConnection tcon;
  protected TopicSession tsession;
  protected TopicPublisher tpublisher;
  protected Topic topic;
  protected TextMessage msg;

  public void init(Context ctx, String topicName) throws NamingException, JMSException
  {
    tconFactory = (TopicConnectionFactory) ctx.lookup(JMS_FACTORY);
    tcon = tconFactory.createTopicConnection();
    tsession = tcon.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
    topic = (Topic) ctx.lookup(topicName);
    tpublisher = tsession.createPublisher(topic);
    msg = tsession.createTextMessage();
    tcon.start();
  }
  
  public void send(String message) throws JMSException
  {
    msg.setText(message);
    tpublisher.publish(msg);
  }

  public void close() throws JMSException
  {
    tpublisher.close();
    tsession.close();
    tcon.close();
  }
   
  public static void main(String[] args) throws Exception 
  {
    if (args.length != 1) {
      System.out.println("Usage: java examples.jms.topic.TopicSend WebLogicURL");
      return;
    }
    InitialContext ic = getInitialContext(args[0]);
    TopicSend ts = new TopicSend();
    ts.init(ic, TOPIC);
    readAndSend(ts);
    ts.close();
  }

  protected static void readAndSend(TopicSend ts) throws IOException, JMSException
  {
    BufferedReader msgStream = new BufferedReader (new InputStreamReader(System.in));
    String line=null;
    do {
      System.out.print("Enter message (\"quit\" to quit): ");
      line = msgStream.readLine();
      if (line != null && line.trim().length() != 0) {
        ts.send(line);
        System.out.println("JMS Message Sent: "+line+"\n");
      }
    } while (line != null && ! line.equalsIgnoreCase("quit"));
  }
  
  protected static InitialContext getInitialContext(String url) throws NamingException
  {
    Hashtable env = new Hashtable();
    env.put(Context.INITIAL_CONTEXT_FACTORY, JNDI_FACTORY);
    env.put(Context.PROVIDER_URL, url);
    env.put("weblogic.jndi.createIntermediateContexts", "true");
    return new InitialContext(env);
  }
}

⌨️ 快捷键说明

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