Advertisement
Guest User

Untitled

a guest
Nov 20th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 13.08 KB | None | 0 0
  1. package pl.polsl.java.kamil.zietek.lab4.network;
  2.  
  3. import java.io.*;
  4. import java.net.*;
  5. import pl.polsl.java.kamil.zietek.lab4.model.Database;
  6.  
  7. /**
  8.  * The server class servicing a single connection
  9.  *
  10.  * @author Kamil Zietek
  11.  * @version 4.0
  12.  */
  13. class SingleService implements Runnable {
  14.  
  15.     /**
  16.      * socket representing connection to the client
  17.      */
  18.     private final Socket socket;
  19.  
  20.     /**
  21.      * buffered input character stream
  22.      */
  23.     private final BufferedReader inFromClient;
  24.  
  25.     /**
  26.      * Formatted output character stream
  27.      */
  28.     private final PrintWriter outToClient;
  29.  
  30.     /**
  31.      * Reference to database
  32.      */
  33.     private Database database;
  34.  
  35.     /**
  36.      * The constructor of instance of the SingleService class.
  37.      *
  38.      * @param socket socket representing connection to the client
  39.      * @param database reference to database
  40.      * @throws IOException ioexception
  41.      */
  42.     public SingleService(Socket socket, Database database) throws IOException {
  43.         this.socket = socket;
  44.         this.database = database;
  45.         outToClient = new PrintWriter(
  46.                 new BufferedWriter(
  47.                         new OutputStreamWriter(
  48.                                 socket.getOutputStream())), true);
  49.         inFromClient = new BufferedReader(
  50.                 new InputStreamReader(
  51.                         socket.getInputStream()));
  52.     }
  53.  
  54.     /**
  55.      * Realizes the service
  56.      */
  57.     @Override
  58.     public void run() {
  59.         try {
  60.             System.out.println(new java.util.Date().toString());
  61.             System.out.print("Client connected: ");
  62.             System.out.println(Thread.currentThread().getName());
  63.             boolean quit = false;
  64.  
  65.             while (!quit) {
  66.                 String str = inFromClient.readLine();
  67.                 str = str.toUpperCase();
  68.  
  69.                 System.out.print(Thread.currentThread().getName());
  70.                 System.out.println(" sent command " + str);
  71.                 switch (str) {
  72.                     case "BUY_TICKET":
  73.                         buyTicketCommand();                                         //5
  74.                         break;
  75.                     case "CHECK_CONNECTION":
  76.                         outToClient.println("OK");
  77.                         break;
  78.                     case "CHECK_DATABASE":
  79.                         if (database == null) {
  80.                             outToClient.println("NO_DATABASE");
  81.                         } else {
  82.                             outToClient.println("OK");
  83.                         }
  84.                         break;
  85.                     case "DRAWING_RESULTS":
  86.                         drawingResultsCommand();                                    //6
  87.                         break;
  88.                     case "GET_NUMBER_OF_PLAYERS":
  89.                         outToClient.println("OK");
  90.                         outToClient.println(database.getNumberOfPlayers());
  91.                         break;
  92.                     case "GET_PLAYER_TICKET":
  93.                         getPlayerTicketCommand();                                   //4
  94.                         break;
  95.                     case "GET_PLAYERS":
  96.                         getPlayersCommand();                                        //3
  97.                         break;
  98.                     case "HELP":                                                    //1
  99.                         helpCommand();
  100.                         break;
  101.                     case "NEW_DRAWING":
  102.                         database.newDrawing();
  103.                         outToClient.println("OK");
  104.                         break;
  105.                     case "QUIT":
  106.                         quit = true;
  107.                         outToClient.println("OK");
  108.                         break;
  109.                     case "REGISTER":
  110.                         registerCommand();                                          //2
  111.                         break;
  112.                     default:
  113.                         System.out.println("Unknown command: " + str);
  114.                         outToClient.println("UNKNOWN_COMMAND");
  115.                         break;
  116.                 }
  117.             }
  118.         } catch (IOException | NullPointerException e) {
  119.             System.err.println(e.getMessage());
  120.         } finally {
  121.             System.out.print("Client disconnected: ");
  122.             System.out.println(Thread.currentThread().getName());
  123.             try {
  124.                 socket.close();
  125.             } catch (IOException e) {
  126.                 System.err.println(e.getMessage());
  127.             }
  128.         }
  129.     }
  130.  
  131.     /**
  132.      * List of available commands, sent to client
  133.      */
  134.     private void helpCommand() {
  135.         outToClient.print("Available commands: ");
  136.         outToClient.print("BUY_TICKET [ID of player]");
  137.         outToClient.print("CHECK_CONNECTION, ");
  138.         outToClient.print("CHECK_DATABASE, [Last drawing or all drawings]");        
  139.         outToClient.print("DRAWING_RESULTS, ");        
  140.         outToClient.print("GET_NUMBER_OF_PLAYERS, ");
  141.         outToClient.print("GET_PLAYER_TICKET [ID of player], ");
  142.         outToClient.print("GET_PLAYERS, ");                                                             //getPlayersCommand
  143.         outToClient.print("HELP, ");
  144.         outToClient.print("NEW_DRAWING, ");
  145.         outToClient.print("QUIT, ");
  146.         outToClient.print("REGISTER [Number of players, NAME, SURNAME and AGE for each player");        //registerCommand
  147.         outToClient.println();
  148.     }
  149.  
  150.     /**
  151.      * Registration of players. First value after REGISTER command must be
  152.      * integer with number of players
  153.      */
  154.     private void registerCommand() {
  155.         if (database == null) {
  156.             outToClient.println("OK");
  157.             Database tmp = null;
  158.             try {
  159.                 String str = inFromClient.readLine();
  160.                 System.out.print(Thread.currentThread().getName());
  161.                 System.out.println(" sent number of players to register: " + str);
  162.                 tmp = new Database(Integer.parseInt(str));
  163.                 for (int i = 0; i < tmp.getNumberOfPlayers(); i++) {
  164.                     outToClient.println("OK_GIVE_NAME");
  165.                     String name = inFromClient.readLine();
  166.                     outToClient.println("OK_GIVE_SURNAME");
  167.                     String surname = inFromClient.readLine();
  168.                     outToClient.println("OK_GIVE_AGE");
  169.                     int age = Integer.parseInt(inFromClient.readLine());
  170.                     tmp.addNewPlayer(i, name, surname, age);
  171.                     outToClient.println("OK_ADDED");
  172.                 }
  173.             } catch (IOException | NumberFormatException ex) {
  174.                 outToClient.println("ERROR");
  175.                 System.out.print(Thread.currentThread().getName());
  176.                 System.out.println(" get error when registering players");
  177.             }
  178.             database = tmp;
  179.             outToClient.println("REGISTER_SUCCESS");
  180.             System.out.print(Thread.currentThread().getName());
  181.             System.out.println(" succesfully registered players.");
  182.         } else {
  183.             outToClient.println("ERROR_ALREADY_REGISTERED");
  184.             System.out.println("Already registered");
  185.         }
  186.     }
  187.  
  188.     /**
  189.      * All players to client sender, first value after GET_PLAYERS command must
  190.      * be ID of specified player
  191.      */
  192.     private void getPlayersCommand() {
  193.         outToClient.println("OK");
  194.         outToClient.println(database.getNumberOfPlayers());
  195.         boolean finish = false;
  196.         int i = 0;
  197.         while (!finish) {
  198.             try {
  199.                 String str = inFromClient.readLine();
  200.                 switch (str) {
  201.                     case "OK_GIVE_NAME":
  202.                         outToClient.println(database.getPlayers()[i].getName());
  203.                         break;
  204.                     case "OK_GIVE_SURNAME":
  205.                         outToClient.println(database.getPlayers()[i].getSurname());
  206.                         break;
  207.                     case "OK_GIVE_AGE":
  208.                         outToClient.println(database.getPlayers()[i].getAge());
  209.                         break;
  210.                     case "OK_GIVE_CREDITS":
  211.                         outToClient.println(database.getPlayers()[i].getCredits());
  212.                         break;
  213.                     case "OK_GET":
  214.                         i++;
  215.                         break;
  216.                     case "GET_PLAYERS_SUCCESS":
  217.                         finish = true;
  218.                         System.out.print(Thread.currentThread().getName());
  219.                         System.out.println(" succesfully sent players.");
  220.                         break;
  221.                 }
  222.             } catch (IOException e) {
  223.                 System.err.println(e.getMessage());
  224.                 System.out.print(Thread.currentThread().getName());
  225.                 System.out.println(" get error when sending players");
  226.             }
  227.         }
  228.  
  229.     }
  230.  
  231.     /**
  232.      * Specified player's ticket sender,
  233.      */
  234.     private void getPlayerTicketCommand() {//ex
  235.         outToClient.println("OK");
  236.         try {
  237.             int i = Integer.parseInt(inFromClient.readLine());
  238.             if (database.getPlayers()[i].getTicket().getResults()[0] == 0) {
  239.                 outToClient.println("NO_TICKET");
  240.             } else {
  241.                 String ticket = null;
  242.                 for (int j = 0; j < database.getPlayers()[i].getTicket().getResults().length; j++) {
  243.                     if (j == 0) {
  244.                         ticket = database.getPlayers()[i].getTicket().getResults()[j] + ", ";
  245.                     } else {
  246.                         ticket += database.getPlayers()[i].getTicket().getResults()[j] + ", ";
  247.                     }
  248.                 }
  249.                 outToClient.println(ticket);
  250.             }
  251.             if (inFromClient.readLine().equals("GIVE_CREDITS")) {
  252.                 outToClient.println(database.getPlayers()[i].getCredits());
  253.             } else {
  254.                 outToClient.println("ERROR");
  255.             }
  256.  
  257.         } catch (IOException | NumberFormatException e) {
  258.             System.err.println(e.getMessage());
  259.         }
  260.     }
  261.  
  262.     /**
  263.      * Buy ticket for specified player
  264.      */
  265.     private void buyTicketCommand() {
  266.         outToClient.println("OK");
  267.         try {
  268.             int i = Integer.parseInt(inFromClient.readLine());
  269.             if (database.buyLotteryTicket(i)) {
  270.                 outToClient.println("OK_BOUGHT");
  271.             } else {
  272.                 outToClient.println("ERROR_BUYING");
  273.             }
  274.         } catch (IOException | NumberFormatException e) {
  275.             System.err.println(e.getMessage());
  276.         }
  277.     }
  278.  
  279.     /**
  280.      * Send all drawing results to client
  281.      */
  282.     private void drawingResultsCommand() {
  283.         outToClient.println("OK");
  284.         String str, tmp;
  285.         boolean finish = false;
  286.         while (!finish) {
  287.             try {
  288.                 str = inFromClient.readLine();
  289.                 switch (str) {
  290.                     case "GET_LAST_DRAWING":
  291.                         int[] results = database.getDrawings().get(database.getDrawings().size() - 1).getResults();
  292.                         tmp = "Results of drawing #" + database.getDrawings().size() + '\n';
  293.                         for (int res : results) {
  294.                             tmp += res + ", ";
  295.                         }
  296.                         tmp += '\n';
  297.                         for (int i = 0; i < database.getNumberOfPlayers(); i++) {
  298.                             int reward = database.checkPlayerReward(i);
  299.                             if (reward > 0) {
  300.                                 tmp += "Player #" + (i + 1) + " hit " + reward + " numbers!\n";
  301.                             } else if (reward == 0) {
  302.                                 tmp += "Player #" + (i + 1) + " hasn't hit any numbers!\n";
  303.                             } else if (reward < 0) {
  304.                                 tmp += "Player #" + (i + 1) + " hasn't bought ticket to this drawing!\n";
  305.                             }
  306.                         }
  307.                         outToClient.println(tmp);
  308.                         outToClient.println("LAST_DRAWING_SENT");
  309.                         break;
  310.  
  311.                     case "GET_ALL_DRAWINGS":
  312.                         tmp = "Results of all drawings:\n";
  313.                         for (int i = database.getDrawings().size() - 1; i >= 0; i--) {
  314.                             tmp += "Drawing #" + (i + 1) + ": ";
  315.                             for (int res : database.getDrawings().get(i).getResults()) {
  316.                                 tmp += res + ", ";
  317.                             }
  318.                             tmp += '\n';
  319.                         }
  320.                         outToClient.println(tmp);
  321.                         outToClient.println("ALL_DRAWINGS_SENT");
  322.                         break;
  323.  
  324.                     case "DRAWINGS_REFRESH_SUCCESS":
  325.                         finish = true;
  326.                         break;
  327.                 }
  328.             } catch (IOException e) {
  329.                 System.err.println(e.getMessage());
  330.             }
  331.         }
  332.     }
  333. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement