Advertisement
donut188

TCPServer.java

Dec 8th, 2013
238
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.53 KB | None | 0 0
  1. import java.io.*;
  2. import java.net.*;
  3. import java.util.*;
  4.  
  5. public class Server
  6. {
  7.     private static int cid;
  8.     private ArrayList<ClientThread> ct;
  9.     private GUIForServer gfs;
  10.     private int port;
  11.     private boolean runForever;
  12.  
  13.     public Server(int port)
  14.     {
  15.         this(port, null);
  16.     }
  17.  
  18.     public Server(int port, GUIForServer gfs)
  19.     {
  20.         this.gfs = gfs;
  21.         this.port = port;
  22.        
  23.         ct = new ArrayList<ClientThread>();
  24.     }
  25.    
  26.     public void start()
  27.     {
  28.         runForever = true;
  29.        
  30.         try
  31.         {
  32.             ServerSocket ss = new ServerSocket(port);
  33.            
  34.             while(runForever)
  35.             {
  36.                 displayMessage("Server waiting for clients on port " + port + ".");
  37.                 Socket s = ss.accept();
  38.                
  39.                 if(!runForever)
  40.                 {
  41.                     break;
  42.                 }
  43.                 ClientThread t1 = new ClientThread(s);
  44.                 ct.add(t1);
  45.                 t1.start();
  46.             }
  47.            
  48.             try
  49.             {
  50.                 ss.close();
  51.                 for(int i = 0; i < ct.size(); i++)
  52.                 {
  53.                     ClientThread cli = ct.get(i);
  54.                     try
  55.                     {
  56.                         cli.ois.close();
  57.                         cli.oos.close();
  58.                         cli.s.close();
  59.                     }
  60.                     catch(IOException ioe)
  61.                     {                      
  62.                     }
  63.                 }
  64.             }
  65.             catch(Exception e)
  66.             {
  67.                 displayMessage("Exception closing the server and client(s): " + e);
  68.             }
  69.         }
  70.         catch(IOException ioe)
  71.         {
  72.             String msg = ("Exception on the new server socket: " + ioe + "\n");
  73.             displayMessage(msg);
  74.         }
  75.     }
  76.    
  77.     protected void stop()
  78.     {
  79.         runForever = false;
  80.        
  81.         try
  82.         {
  83.             new Socket("localhost", port);
  84.         }
  85.         catch(Exception e)
  86.         {
  87.         }
  88.     }
  89.    
  90.     private void displayMessage(String msg)
  91.     {
  92.         String message = msg;
  93.         if(gfs == null)
  94.         {
  95.             System.out.println(msg);
  96.         }
  97.         else
  98.         {
  99.             gfs.eventTextArea(message + "\n");
  100.         }
  101.     }
  102.    
  103.     private synchronized void broadcastToAll(String message)
  104.     {
  105.         String newMessage = message + "\n";
  106.        
  107.         if(gfs == null)
  108.         {
  109.             System.out.print(newMessage);
  110.         }
  111.         else
  112.         {
  113.             gfs.chatTextArea(newMessage);
  114.         }
  115.        
  116.         for(int i = ct.size(); --i >= 0;)
  117.         {
  118.             ClientThread cthr = ct.get(i);
  119.            
  120.             if(!cthr.writeMessage(newMessage))
  121.             {
  122.                 ct.remove(i);
  123.                 displayMessage("The client that disconnected: " + cthr.username + " has been removed from the list of clients that connected.");
  124.                
  125.             }
  126.         }
  127.     }
  128.    
  129.     private synchronized void removeClient(int id)
  130.     {
  131.         for (int i = 0; i < ct.size(); i++) {
  132.             ClientThread cthr = ct.get(i);
  133.            
  134.             if(cthr.id == id)
  135.             {
  136.                 ct.remove(i);
  137.                 return;
  138.             }
  139.         }
  140.     }
  141.    
  142.    
  143.     public static void main (String[] args)
  144.     {
  145.         int portNum = 7257;
  146.         switch(args.length)
  147.         {
  148.             case 0:
  149.             break;
  150.            
  151.             case 1:
  152.             try
  153.             {
  154.                 portNum = Integer.parseInt(args[0]);
  155.             }
  156.             catch(Exception e)
  157.             {
  158.                 System.out.println("Invalid port number.");
  159.                 System.out.println("Usage of this program is as follows: -> java Server (portNum)");
  160.                 return;
  161.             }
  162.            
  163.             default:
  164.             System.out.println("Usage of this program is as follows: -> java Server (portNum)");            
  165.             return;
  166.         }
  167.         Server server = new Server(portNum);
  168.         server.start();
  169.     }
  170.    
  171.     public class ClientThread extends Thread
  172.     {
  173.         Socket s;
  174.         ObjectInputStream ois;
  175.         ObjectOutputStream oos;
  176.         int id;
  177.         String username;
  178.         messageType mt;
  179.        
  180.         public ClientThread(Socket s)
  181.         {
  182.             id = cid++;
  183.             this.s = s;
  184.            
  185.             System.out.println("Thread is trying to create object Input or Output streams...");
  186.             try
  187.             {
  188.                 oos = new ObjectOutputStream(s.getOutputStream());
  189.                 ois = new ObjectInputStream(s.getInputStream());
  190.                 username = (String) ois.readObject();
  191.                 displayMessage(username + " has connected.");
  192.             }
  193.             catch(IOException ioe)
  194.             {
  195.                 displayMessage("Exception creating new input or output streams: " + ioe);
  196.                 return;
  197.             }
  198.             catch(ClassNotFoundException cnfe)
  199.             {
  200.             }
  201.         }
  202.        
  203.         public void run()
  204.         {
  205.             boolean runForever = true;
  206.             while(runForever)
  207.             {
  208.                 try
  209.                 {
  210.                     mt = (messageType) ois.readObject();
  211.                 }
  212.                 catch(IOException ioe)
  213.                 {
  214.                     displayMessage(username + " has an exception reading streams: " + ioe);
  215.                     break;
  216.                 }
  217.                 catch(ClassNotFoundException cnfe)
  218.                 {
  219.                     break;
  220.                 }
  221.                
  222.                 String message = mt.getMessage();
  223.                
  224.                 switch(mt.getType())
  225.                 {
  226.                     case messageType.MESSAGE:
  227.                     broadcastToAll(username + "'s message: " + message);
  228.                     break;
  229.                    
  230.                     case messageType.EXIT:
  231.                     displayMessage(username + "exited by typing EXIT.");
  232.                     runForever = false;
  233.                     break;
  234.                 }
  235.             }
  236.            
  237.             removeClient(id);
  238.             close();
  239.         }
  240.        
  241.         public void close()
  242.         {
  243.             try
  244.             {
  245.                 if(oos != null)
  246.                 {
  247.                     oos.close();
  248.                 }
  249.             }
  250.             catch(Exception e)
  251.             {
  252.             }
  253.            
  254.             try
  255.             {
  256.                 if(ois != null)
  257.                 {
  258.                     ois.close();
  259.                 }
  260.             }
  261.             catch(Exception e)
  262.             {
  263.             }
  264.            
  265.             try
  266.             {
  267.                 if(s != null)
  268.                 {
  269.                     s.close();
  270.                 }
  271.             }
  272.             catch(Exception e)
  273.             {
  274.             }        
  275.         }
  276.        
  277.         private boolean writeMessage(String msg)
  278.         {
  279.             if(!s.isConnected())
  280.             {
  281.                 close();
  282.                 return false;
  283.             }
  284.            
  285.             try
  286.             {
  287.                 oos.writeObject(msg);
  288.             }
  289.             catch(IOException ioe)
  290.             {
  291.                 displayMessage("Error sending message to " + username + "!");
  292.                 displayMessage(ioe.toString());
  293.             }
  294.             return true;
  295.         }
  296.     }
  297. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement