Programming message services in Java

Asynchronous interactions seem to be the way of the future

At this point, the client will have sent a message to the JMS message server available within the JBoss application server.

The complete JMS client is presented below, based on the above description:

package com.regdeveloper.jms.client;

import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

public class NewsClient {

   public static void main(String [] args) throws Exception {
      if (args.length == 0) {
         printUsage();
      } else {
         String text = args[0];
         System.out.println("Sending Msg: " + text);
         
         Context context = new InitialContext();
         System.out.println("Got Initial Context");
         // Get connection factory from naming service
         QueueConnectionFactory f =  
                 (QueueConnectionFactory)
                            context.lookup("ConnectionFactory");
         System.out.println("Obtained queue connection factory");
         // Create the connection
         QueueConnection qc = f.createQueueConnection();
         System.out.println("Obtained the queue connection");
         // Create the session
         QueueSession qs = 
             qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
         System.out.println("Obtained the queue session");
         // Note queue must be placed before the queue name
         Queue q = (Queue)context.lookup("queue/testQueue");
         System.out.println("Obtained the queue: " +
                                q.getQueueName());
         QueueSender sender = qs.createSender(q);
         TextMessage message = qs.createTextMessage();
         message.setText(text);
         System.out.println("Sending message to queue");
         sender.send(q, message);
         System.out.println("Message sent");
         // Must close the connection
         qc.close();
      }  
   }
   public static void printUsage() {  
         System.out.println("java NewsClient <message>"); 
   }
}

Sponsored: Network DDoS protection

Next page: The consumer