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

📄 chatclient.java

📁 分别介绍RMI,分布式对象与CORBA,动态接口,CORBA客户端开发的课件,以及相关的例子
💻 JAVA
字号:
/*
 * Copyright 1999 by dreamBean Software,
 * All rights reserved.
 */
package masteringrmi.chat.client;

import java.io.IOException;
import java.net.MalformedURLException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.ServerException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Properties;
import java.util.Iterator;
import java.util.StringTokenizer;

import javax.swing.ListModel;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.SwingUtilities;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import masteringrmi.chat.interfaces.Message;
import masteringrmi.chat.interfaces.MessageListener;
import masteringrmi.chat.interfaces.Topic;
import masteringrmi.chat.interfaces.TopicInfo;
import masteringrmi.chat.interfaces.TopicServer;
import masteringrmi.chat.interfaces.ListenerInfo;

/**
 *   This is the chat client model and controller. This is used
 *   by the GUI, but can also be used as a standalone application
 *   for testing purposes.
 *      
 *   @see ChatGUI
 *   @author Rickard 謆erg (rickard@dreambean.com)
 *   @version $Revision:$
 */
public class ChatClient
   extends UnicastRemoteObject
   implements MessageListener
{
   // Constants -----------------------------------------------------
   static final String TOPIC_SERVER = "topics";
    
   // Attributes ----------------------------------------------------
   TopicServer server;
   
   DefaultComboBoxModel topics;
   DefaultListModel users;
   
   Topic currentTopic;
   TopicInfo currentTopicInfo;
   ListenerInfo info;
   String title;
   
   MessageReceiver messageReceiver;
   
   // Static --------------------------------------------------------
   public static void main(String[] args)
      throws IOException
   {
      // Performance tests
      // This will test the throughput of the chat system
      // Typically you should get about 0 ms/message (i.e. very low)
      // The reason for this is that since the message delivery is 
      // batched there will be a number of messages for each RMI call
   
      // Set security policy and security manager
      // Policy allows everything

      System.setProperty("java.security.policy",ChatClient.class.getResource("/client.policy").toString());

      System.setSecurityManager(new SecurityManager());
   
      // Get test parameters
      int clientCount = new Integer(args[0]).intValue();
      int messageCount = new Integer(args[1]).intValue();
      int topicIndex = args.length == 3 ? new Integer(args[2]).intValue()-1 : 0;
      
      // Create test clients and subscribe them to the default topic
      Collection clients = new ArrayList();
      ChatClient client = null;
      for (int i = 0; i < clientCount; i++)
      {
         client = new ChatClient();
         client.login("Hello"+i);
         client.subscribe(((TopicInfo)client.getTopics().getElementAt(topicIndex)));
         clients.add(client);
         System.out.println("Client "+i+" created");
      }
      
      System.out.println("Clients created");
      
      // Use the last client to send messages
      long start = System.currentTimeMillis();
      for (int i = 0; i < messageCount; i++)
      {
         Message message = new Message("Hello"+(clientCount-1),"Text","Hello "+i+"!");
         client.publishMessage(message);
         if (i % 100 == 0)
            System.out.println(i+" messages sent");
      }
      long end = System.currentTimeMillis();
      long time = end - start;
      System.out.println("Test done");
      

      // Log off test clients
      Iterator enumtest = clients.iterator();
      while (enumtest.hasNext())
      {
         client = (ChatClient)enumtest.next();
         client.logout();
      }
      
      System.out.println("Clients removed");
      
      // Show results
      System.out.println("Total time:"+time);
      System.out.println("Nr of clients:"+clientCount);
      System.out.println("Total nr of messages:"+(messageCount*(clientCount+1)));
      System.out.println("Time/message:"+(time/messageCount));
      System.out.println("Time/(message*nr of test clients):"+(time/(messageCount*clientCount)));
      System.out.println("Time/(message*(nr of test clients + 1)):"+(time/(messageCount*(clientCount+1))));
   }
   
   // Constructors --------------------------------------------------
   public ChatClient()
      throws IOException
   {
      getTopicServer();
   }

   // Public --------------------------------------------------------
   public void login(String name)
      throws RemoteException
   {
      info = new ListenerInfo(name);
      
      getTopicServer().addListener(info, this);
   }
   
   public void logout()
      throws RemoteException
   {
      if (currentTopic != null)
         unsubscribe();
         
      getTopicServer().removeListener(info);
      server = null;
   }

   public void subscribe(TopicInfo topicInfo)
      throws RemoteException
   {
      if (currentTopic != null)
         unsubscribe();
      
      currentTopic = server.subscribe(topicInfo, info);
      currentTopicInfo = topicInfo;
      
      // Force user list to be loaded
      getUsers();
   }
   
   public void unsubscribe()
      throws RemoteException
   {
      server.unsubscribe(currentTopicInfo, info);
      currentTopic = null;
      currentTopicInfo = null;
      users = null;
   }
   
   public void publishMessage(Message message)
      throws RemoteException
   {
      currentTopic.publishMessage(message);
   }
   
   public void addMessageReceiver(MessageReceiver mr)
   {
      this.messageReceiver = mr;
   }
   
   public void removeMessageReceiver(MessageReceiver mr)
   {
      if (this.messageReceiver == mr)
         this.messageReceiver = null;
   }
   
   public TopicServer getTopicServer()
      throws RemoteException
   {
      if (server == null)
      {
         try
         {
            Properties cfg = new Properties();
            cfg.load(getClass().getResourceAsStream("/jndi.properties"));
            server = (TopicServer)new InitialContext(cfg).lookup(TOPIC_SERVER);
         } catch (NamingException e)
         {
            throw new ServerException("Could not access topic server", e);
         } catch (IOException e)
         {
            throw new ServerException("Could not load jndi.properties", e);
         }
         
         // Get topic list from server
         topics = new DefaultComboBoxModel();
         Iterator enumtest = getTopicServer().getTopicInfos().iterator();
         while(enumtest.hasNext())
         {
            topics.addElement(enumtest.next());
         }
      }
      
      return server;
   }
   
   public ComboBoxModel getTopics()
      throws RemoteException
   {
      return topics;
   }
   
   public ListModel getUsers()
      throws RemoteException
   {
      // Get list from server
      if (users == null)
      {
         users = new DefaultListModel();
         Iterator enumtest = currentTopic.getListenerInfos().iterator();
         while(enumtest.hasNext())
         {
            users.addElement(enumtest.next());
         }
      }
      
      return users;
   }
   
   public ListenerInfo getClientInfo()
   {
      return info;
   }
   
   // MessageListener implementation --------------------------------
   public synchronized void messagePublished(final Collection messages)
   {
      SwingUtilities.invokeLater(new Runnable()
      {
         public void run()
         {
            try
            {
               Iterator enumtest = messages.iterator();
               while (enumtest.hasNext())
               {
                  messagePublished((Message)enumtest.next());
               }
            } catch (Exception e)
            {
               e.printStackTrace();
            }
         }
      });
   }   
   
   public synchronized void messagePublished(Message message)
   {
      if (server == null)
      {
         // Not connected - ignore
         return;
      }
      
      try
      {
         if (message.getSender().equals(Message.SYSTEM))
         {
            // System messages
            if (message.getType().equals(Message.TOPIC_CREATED))
            {
               ((DefaultComboBoxModel)getTopics()).addElement(message.getContent());
            } else if (message.getType().equals(Message.TOPIC_REMOVED))
            {
               ((DefaultComboBoxModel)getTopics()).removeElement(message.getContent());
            } else if (message.getType().equals(Message.USER_JOINED))
            {
               if (currentTopic == null) 
                  return; // Ignore
               
               ((DefaultListModel)getUsers()).addElement(message.getContent());
            } else if (message.getType().equals(Message.USER_LEFT))
            {
               if (currentTopic == null) 
                  return; // Ignore
               
               ((DefaultListModel)getUsers()).removeElement(message.getContent());
            } else
            {
               // Normal message
               addMessage(message);
            } 
         } else
         {
            // Normal message
            addMessage(message);
         }
      } catch (RemoteException e)
      {
         e.printStackTrace();
      }
   }   
   
   // Protected -----------------------------------------------------
   void addMessage(Message message)
   {
      if (messageReceiver != null)
         messageReceiver.handleMessage(message);
   }
    
   void addMessage(Throwable error)
   {
      error.printStackTrace();
      addMessage(new Message(Message.SYSTEM, Message.TEXT, error.toString()));
   }
   
   // Inner classes -------------------------------------------------
   public interface MessageReceiver
   {
      public void handleMessage(Message message);
   }
}

⌨️ 快捷键说明

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