document.write('
Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. package Chatroom;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.io.PrintWriter;
  7. import java.net.ServerSocket;
  8. import java.net.Socket;
  9. import java.util.HashSet;
  10.  
  11. /**
  12.  * This is the main server class. It is the core of the server functionality, and the listener for incoming clients that will
  13.  * spawn threads to deal with clients, track their information, change their states and ultimately, clean up after all clients by keeping the
  14.  * data structures up to date.
  15.  * @version 0.1
  16.  *
  17.  */
  18. public class Server {
  19.     public static final int PORT = 9001; //fixed port to be used by the server for now
  20.     /**
  21.      * The set of all names of clients in the main room.
  22.      */
  23.     private static HashSet<String> names = new HashSet<String>();
  24.    
  25.     /**
  26.      * The set of all the print writers for all the clients. This is kept so we can easily broadcast messages.
  27.      */
  28.     private static HashSet<PrintWriter> writers = new HashSet<PrintWriter>();
  29.    
  30.     /**
  31.      * The application\'s main method, which listens on the specified port and spawns handler threads
  32.      */
  33.     public static void main(String[] args) throws Exception {
  34.         ServerLogger.log("Server started.");
  35.         ServerSocket listener = new ServerSocket(PORT);
  36.         try {
  37.             while (true) {
  38.                 new Handler(listener.accept()).start();
  39.             }
  40.         } finally {
  41.             listener.close();
  42.         }
  43.     }
  44.    
  45.     /**
  46.      * A handler thread class. Handlers are spawned from the listening loop and are responsible for
  47.      * dealing with a single client and broadcasting its messages.
  48.      */
  49.     private static class Handler extends Thread {
  50.         private String name; //Holds the username of this client only after authenticating.
  51.         private Socket socket;
  52.         private BufferedReader in;
  53.         private PrintWriter out;
  54.         public User user;
  55.         private UserState state; //The state that the user is currently in. This is used for masking certain actions, and only allow those actions appropriate for
  56.         //this user state. For example a user in a game cannot accept invitations by other players. A user in the lobby cannot make a player move command.
  57.        
  58.         /**
  59.          * Constructs a handler thread. All the interesting work is done in the run method.
  60.          */
  61.         public Handler(Socket socket) {
  62.             this.socket = socket; //the supplied Socket is the one made when the listener accepted a client.
  63.         }
  64.        
  65.         public void run() {
  66.             try {
  67.                 //Create character streams for the socket.
  68.                 in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  69.                 out = new PrintWriter(socket.getOutputStream(), true);
  70.                
  71.                 //First, authenticate user and keep his user details.
  72.                 while(true) {
  73.                     out.println( "" + OpCodeSC.AUTHENTICATE.ordinal()); //Ask for authentication
  74.                     String response = in.readLine(); //Read client response (should contain user and pass). User can disconnect at this point.
  75.                     int opCode = Integer.parseInt(response.split("-|")[0]);
  76.                     String subString = response.split("-|")[1];
  77.                     if (opCode == OpCodeCS.AUTHENTICATE.ordinal() && MessageHandler.dispatch(opCode, subString, null) == true){
  78.                         out.println("Authentication succesful.");
  79.                         break;
  80.                     }
  81.                     else {
  82.                         out.println("Authentication not succesful.");
  83.                     }
  84.                     //TODO: Fix to ensure proper user states and corresponding masking vectors for allowed actions.
  85.                 }
  86.                
  87.                 //Second, keep accepting client messages, handling them, and sending responses.
  88.                
  89.                 while(true){
  90.                     String response = in.readLine();
  91.                     //Dissasemble and handle all client input.
  92.                     int opcode = Integer.parseInt(response.split("-|")[0]);
  93.                     String subString = response.split("-|")[1];
  94.                     MessageHandler.dispatch(opcode, subString, null);
  95.                 }
  96.                
  97.             } catch (IOException e) {
  98.                 ServerLogger.log(e.toString());
  99.             } finally {
  100.                 //This client is going down. Remove its name and print writer from the sets, and close its socket.
  101.                 if (name != null) {
  102.                     names.remove(name);
  103.                 }
  104.                 if (out != null) {
  105.                     writers.remove(out);
  106.                 }
  107.                 ServerLogger.log("Client closed connection.");
  108.                 try {
  109.                     socket.close();
  110.                 } catch (IOException e) {
  111.                     ServerLogger.log("Failed closing socket for a client that disconnected");
  112.                 }
  113.             }
  114.            
  115.            
  116.         }
  117.     }
  118. }
');