Wednesday, July 18, 2012

Simple Chat Program

For my final project in networking I created a simple Server/Client Chat Program. This is the final version of the server side code.


//Necessary Libraries
import java.io.*;
import java.net.*;
import java.util.*;


//The Server Class contains all the classes and functions that
//this Chat Server needs to run
//Start this Class by calling the startHostingServer Function
class Server
{
    //Holds the Socket connections with the Clients
    private ArrayList connections;
    
    private ArrayList dirtyWords;
        
    //Class that will Handle the Client Connection
    //This is a thread to allow multiple clients to
    //be handled concurrently
    public class ClientHandler implements Runnable
    {
        //Buffered reader for input from the Client
        BufferedReader reader;
        
        //The socket connection to the Client
        Socket sock;
        
        //The Constructor that will be used when creating a instance
        //of this class.  It takes as a parameter the Socket that
        //has been set up with the Client
        public ClientHandler(Socket clientSocket)
        {
            try
            {
                //Sets up sock and reader
                sock = clientSocket;
                InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
                reader = new BufferedReader(isReader);
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
        
        //This is what is run when the Thread is started
        //Gets any messages from the client and lets all the other clients
        //on this server know what the message is
        public void run()
        {
            String message;
            try
            {
                while((message = reader.readLine()) != null)
                {
                    tellEveryone(filterMessage(message));
                }
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
    
    //This is what is called to start the server
    //Creates a new StartServer and starts the getConnections
    //function
    //This is called by the StartHosting Class
    public void startHostingServer(int portNumber)
    {
        StartServer server = new StartServer();
        server.setupDirtyWords();
        server.getConnections(portNumber);
    }
    
    //This is the StartServer Class
    //This starts the server and gets connections to the clients
    public class StartServer
    {
        //This Sets up the dictionary that will be used to filter out
        //the dirty words that may be used
        public void setupDirtyWords()
        {
            dirtyWords = new ArrayList();
            try
            {
                //This is the file where the list of dirty words
                //are located at
                File dwFile = new File("dirtyWords.txt");
                FileReader fileReader = new FileReader(dwFile);
                BufferedReader bufReader = new BufferedReader(fileReader);
                
                String word;
                while((word = bufReader.readLine()) != null)
                {
                    dirtyWords.add(word + " ");
                }
                bufReader.close();
                
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
        
        //Accepts Client Connections to the Server
        public void getConnections(int portNumber)
        {
            
            try
            {
                //Create the WelcomSocket for the Server to recieve Connections
                ServerSocket welcomeSocket;
                welcomeSocket = new ServerSocket(portNumber);
                
                //Initializes the connections ArrayList
                connections = new ArrayList();
            
                //This is continually run to continue accepting connections for
                //any host that may want to join
                while(true)
                {
                    Socket clientSocket = welcomeSocket.accept();
                    PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
                    connections.add(writer);
                    Thread t = new Thread(new ClientHandler(clientSocket));
                    t.start();
                }
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
        
    }
    
    //send the message to everyone
    public void tellEveryone(String message)
    {
        Iterator it = connections.iterator();
        while(it.hasNext())
        {
            try
            {
                PrintWriter writer = (PrintWriter) it.next();
                writer.println(message);
                writer.flush();
            }
            catch(Exception ex)
            {
                ex.printStackTrace();
            }
        }
    }
    
    //This is the actual filtering of the message
    //This goes through the list of dirty words and makes sure
    //none of those words are present in the message
    public String filterMessage(String message)
    {
        for (int loop = 0; loop < dirtyWords.size(); loop++)
        {
            message = message.replaceAll(dirtyWords.get(loop).toString(), "*censored*");
        }
        return message;
    }
}


//END OF LINE

Tuesday, July 3, 2012

Just looking at some of the projects I've worked on in the past. One of my favorite was a group project me and some guys from some of my classes did was this networked bingo game. You can download the .jar files and view all the source code here.

We used threads to run the server based part (originally it was a stand alone game and then we networked it, so we tried to keep most of the original structure intact). Here's the run function:


public void run()
   {
      try
      {
         //Set the port number
         int port = 1352;

         //Establish the listen socket.
         ServerSocket welcomeSocket = new ServerSocket(port);


         InetAddress addr = InetAddress.getLocalHost();
         String ip = addr.getHostAddress();

         mMessage.setText("   Server IP Address: " + ip);

         //Process service requests in an infinite loop
         while (true)
         {
            //Listen for a TCP connection request
            Socket connectionSocket = welcomeSocket.accept();
            // Construct an object to process the request.
            BingoHandler request = new BingoHandler(connectionSocket);
            // Create a new thread to process the request.
            Thread thread = new Thread(request);
            // Start the thread.
            thread.start();
         }
      }
      catch (Exception e)
      {
      }
   }


Some simple stuff, but we were really proud to get it working.

//END OF LINE