daily pastebin goal
73%
SHARE
TWEET

Untitled

a guest Oct 23rd, 2017 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. ##some info
  2.  
  3. The client operates with request - responses.
  4. It may also receive broadcast messages from the server so I created a thread that waits for all responses and acts accordingly.
  5.  
  6. ##Client Socket (main thread)
  7. package game_actions;
  8. import java.io.BufferedReader;
  9. import java.io.BufferedWriter;
  10. import java.io.IOException;
  11. import java.io.InputStreamReader;
  12. import java.io.OutputStreamWriter;
  13. import java.net.Socket;
  14. import java.net.UnknownHostException;
  15. import java.util.Scanner;
  16.  
  17. import classes.PanelSocket;
  18.  
  19. public class ClientSocket extends Thread {
  20.     private String host;
  21.     private int port;
  22.     //private BufferedReader bufferedReader;
  23.     private BufferedWriter bufferedWriter;
  24.     private static Socket socket;
  25.     private String token;
  26.     private PanelSocket panel;
  27.     private static ClientSocketSrvHandler client_sck_srv_handler;
  28.     /**
  29.      * Constructs a client that will connect to a server with the given host and port
  30.      * @param host the IP address for the connection to the server
  31.      * @param port the port for the connection to the server
  32.      * @throws IOException
  33.      * @throws UnknownHostException
  34.      */
  35.     public ClientSocket(String host, int port) throws UnknownHostException, IOException {
  36.         this.host = host;
  37.         this.port = port;
  38.         System.out.println("Connecting to server. Host: " + host + " - port: " + port);
  39.         socket = new Socket(host, port);
  40.         System.out.println("Connected.");
  41.         //bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  42.         bufferedWriter = new BufferedWriter(
  43.                 new OutputStreamWriter(socket.getOutputStream()));
  44.         panel = new PanelSocket(this);
  45.     }
  46.    
  47.     /**
  48.      * Starts the client.
  49.      * @throws UnknownHostException if the IP address could not be determined.
  50.      * @throws InterruptedException if the thread is interrupted while sleeping.
  51.      */
  52.     public void run() {
  53.         /*ClientSocketSrvHandler client_sck_srv_handler = new ClientSocketSrvHandler(socket, this);
  54.         client_sck_srv_handler.start();*/
  55.         Scanner scan = new Scanner(System.in);
  56.           String clientCommand;
  57.           boolean registerLoginLoop = true;
  58.           while(registerLoginLoop){
  59.             System.out.print("Choose action:\n0. close connection\n1. creaUtente\n2. login\n");
  60.             clientCommand = scan.next();
  61.             switch(Integer.parseInt(clientCommand)){
  62.                 case 0: try {
  63.                     socket.close();
  64.                 } catch (IOException e) {
  65.                     // TODO Auto-generated catch block
  66.                     e.printStackTrace();
  67.                 }
  68.                     System.out.println("Terminating client.");
  69.                     break;
  70.                 case 1: try {
  71.                     askCreaUtente();
  72.                 } catch (IOException e) {
  73.                     // TODO Auto-generated catch block
  74.                     e.printStackTrace();
  75.                 } catch (InterruptedException e) {
  76.                     // TODO Auto-generated catch block
  77.                     e.printStackTrace();
  78.                 }
  79.                     break;
  80.                 case 2:
  81.                 try {
  82.                     if (askLogin()) {
  83.                         registerLoginLoop = false;
  84.                     }
  85.                 } catch (IOException e) {
  86.                     // TODO Auto-generated catch block
  87.                     e.printStackTrace();
  88.                 } catch (InterruptedException e) {
  89.                     // TODO Auto-generated catch block
  90.                     e.printStackTrace();
  91.                 }
  92.                     break;
  93.               default: System.out.print("Please enter a valid choice.\n");
  94.             }
  95.           }
  96.           boolean actionLoop = true;
  97.           while(actionLoop){
  98.             System.out.print("Choose action:\n1. creaRazza\n2. accessoPartita\n3. mappaGenerale\n4. listaGiocatori\n5. classifica\n6. uscitaPartita\n7. logout\n");
  99.             //TODO: molte azioni ritornano boolean - in futuro, forse potrebbero ritornare void
  100.             clientCommand = scan.next();
  101.             /*if (bufferedReader.ready()) {
  102.                 String server_msg = bufferedReader.readLine();
  103.                 System.out.println("server sent message" + server_msg);
  104.             }*/
  105.             switch(Integer.parseInt(clientCommand)){
  106.               case 1: try {
  107.                     askCreaRazza();
  108.                 } catch (IOException e) {
  109.                     // TODO Auto-generated catch block
  110.                     e.printStackTrace();
  111.                 } break;
  112.               case 2: try {
  113.                     accessoPartita();
  114.                 } catch (IOException e) {
  115.                     // TODO Auto-generated catch block
  116.                     e.printStackTrace();
  117.                 } break;
  118.               case 3: try {
  119.                     mappaGenerale();
  120.                 } catch (IOException e) {
  121.                     // TODO Auto-generated catch block
  122.                     e.printStackTrace();
  123.                 } break;
  124.               case 4: try {
  125.                     listaGiocatori();
  126.                 } catch (IOException e) {
  127.                     // TODO Auto-generated catch block
  128.                     e.printStackTrace();
  129.                 } break;
  130.               case 5: try {
  131.                     classifica();
  132.                 } catch (IOException e) {
  133.                     // TODO Auto-generated catch block
  134.                     e.printStackTrace();
  135.                 } break;
  136.               case 6: try {
  137.                     uscitaPartita();
  138.                 } catch (IOException e) {
  139.                     // TODO Auto-generated catch block
  140.                     e.printStackTrace();
  141.                 } break;
  142.               case 7: try {
  143.                     logout();
  144.                 } catch (IOException e) {
  145.                     // TODO Auto-generated catch block
  146.                     e.printStackTrace();
  147.                 } break;
  148.               default: System.out.print("Please enter a valid choice.\n");
  149.             }
  150.           }
  151.     }
  152.    
  153.     public boolean askCreaUtente() throws IOException, InterruptedException {
  154.         Scanner scan = new Scanner(System.in);
  155.        
  156.         System.out.print("Username:\n");
  157.         String username = scan.next();
  158.         System.out.print("Password:\n");
  159.         String password = scan.next();
  160.         String command = "@creaUtente,user="+username+",pass="+password;
  161.         bufferedWriter.write(command);
  162.         bufferedWriter.newLine();
  163.         bufferedWriter.flush();
  164.         String answer = client_sck_srv_handler.getResponse();
  165.         if (answer != null) {
  166.             System.out.println("Server response: " + answer);
  167.             if (answer.equals("@ok")){
  168.                 return true;
  169.             }
  170.         }
  171.         return false;
  172.     }
  173.    
  174.     public boolean askLogin() throws IOException, InterruptedException {
  175.         Scanner scan = new Scanner(System.in);
  176.        
  177.         System.out.print("Username:\n");
  178.         String username = scan.next();
  179.         System.out.print("Password:\n");
  180.         String password = scan.next();
  181.         String command = "@login,user="+username+",pass="+password;
  182.         bufferedWriter.write(command);
  183.         bufferedWriter.newLine();
  184.         bufferedWriter.flush();
  185.         String answer = client_sck_srv_handler.getResponse();
  186.         if (answer != null) {
  187.             System.out.println("Server response: " + answer);
  188.             if (answer.startsWith("@ok")){
  189.                 //save the token
  190.                 String[] splitted = answer.split(",");
  191.                 this.token = splitted[1];
  192.                 System.out.println("token received: " + this.token);
  193.                 return true;
  194.             }
  195.         }
  196.         return false;
  197.     }
  198.    
  199.     public boolean askCreaRazza() throws IOException {
  200.         Scanner scan = new Scanner(System.in);
  201.        
  202.         System.out.print("Species Name:\n");
  203.         String species_name = scan.next();
  204.         System.out.print("Species Type (c or e):\n");
  205.         String species_type = scan.next();
  206.         String command = "@creaRazza,token="+this.token+",nome="+species_name+",tipo="+species_type;
  207.         System.out.println("command: "+command);
  208.         bufferedWriter.write(command);
  209.         bufferedWriter.newLine();
  210.         bufferedWriter.flush();
  211.         String answer = bufferedReader.readLine();
  212.         if (answer != null) {
  213.             System.out.println("Server response: " + answer);
  214.             /*if (answer.equals("@ok")){
  215.                 return true;
  216.             }*/
  217.         }
  218.         return false;
  219.     }
  220.    
  221.     public boolean accessoPartita() throws IOException {
  222.         String command = "@accessoPartita,token="+this.token;
  223.         bufferedWriter.write(command);
  224.         bufferedWriter.newLine();
  225.         bufferedWriter.flush();
  226.         String answer = bufferedReader.readLine();
  227.         if (answer != null) {
  228.             System.out.println("Server response: " + answer);
  229.             /*if (answer.equals("@ok")){
  230.                 return true;
  231.             }*/
  232.         }
  233.         return false;
  234.     }
  235.    
  236.     public boolean mappaGenerale() throws IOException {
  237.         String command = "@mappaGenerale,token="+this.token;
  238.         bufferedWriter.write(command);
  239.         bufferedWriter.newLine();
  240.         bufferedWriter.flush();
  241.         String answer = bufferedReader.readLine();
  242.         if (answer != null) {
  243.             System.out.println("Server response: " + answer);
  244.             if (answer.startsWith("@mappaGenerale")){
  245.                 System.out.println("Rendering map...");
  246.                 String[] mappa = answer.split("},");
  247.                 String mappachars = mappa[1];
  248.                 /*mappachars = mappachars.replaceAll("(\\[)", "");
  249.                 mappachars = mappachars.replaceAll("(\\])", "");*/
  250.                 panel.showPanel(mappachars);
  251.             }
  252.         }
  253.         return false;
  254.     }
  255.    
  256.     public boolean muoviDinosauro(String id_dino, String dest) throws IOException { //TODO cambiare string dest - forse ritorno da cambiare in String o simile
  257.         String command = "@muoviDinosauro,token="+this.token+",idDino="+id_dino+",dest="+dest;
  258.         bufferedWriter.write(command);
  259.         bufferedWriter.newLine();
  260.         bufferedWriter.flush();
  261.         String answer = bufferedReader.readLine();
  262.         if (answer != null) {
  263.             System.out.println("Server response: " + answer);
  264.             if (answer.startsWith("@ok")){
  265.                 //movimento possibile - spostare dinosauro panel
  266.             }
  267.             else
  268.             if (answer.startsWith("@combattimento")){
  269.                 //battle! - eliminare dinosauro perdente dalla mappa
  270.             }
  271.             else
  272.                 return false;
  273.         }
  274.         return false;
  275.     }
  276.    
  277.     public String vistaLocale(String dino_id) throws IOException {
  278.         String command = "@vistaLocale,token="+this.token+",idDino="+dino_id;
  279.         System.out.println(command);
  280.         bufferedWriter.write(command);
  281.         bufferedWriter.newLine();
  282.         bufferedWriter.flush();
  283.         String answer = bufferedReader.readLine();
  284.         if (answer != null) {
  285.             System.out.println("Server response: " + answer);
  286.             return answer;
  287.         }
  288.         return null;
  289.     }
  290.    
  291.     public String listaDinosauri() throws IOException {
  292.         String command = "@listaDinosauri,token="+this.token;
  293.         System.out.println(command);
  294.         bufferedWriter.write(command);
  295.         bufferedWriter.newLine();
  296.         bufferedWriter.flush();
  297.         String answer = bufferedReader.readLine();
  298.         if (answer != null) {
  299.             System.out.println("Server response: " + answer);
  300.             return answer;
  301.         }
  302.         return null;
  303.     }
  304.    
  305.     public String statoDinosauro(String dino_id) throws IOException {
  306.         String command = "@statoDinosauro,token="+this.token+",idDino="+dino_id;
  307.         System.out.println(command);
  308.         bufferedWriter.write(command);
  309.         bufferedWriter.newLine();
  310.         bufferedWriter.flush();
  311.         String answer = bufferedReader.readLine();
  312.         if (answer != null) {
  313.             System.out.println("Server response: " + answer);
  314.             return answer;
  315.         }
  316.         return null;
  317.     }
  318.    
  319.     public boolean listaGiocatori() throws IOException {
  320.         String command = "@listaGiocatori,token="+this.token;
  321.         System.out.println(command);
  322.         bufferedWriter.write(command);
  323.         bufferedWriter.newLine();
  324.         bufferedWriter.flush();
  325.         String answer = bufferedReader.readLine();
  326.         if (answer != null) {
  327.             System.out.println("Server response: " + answer);
  328.             /*if (answer.equals("@ok")){
  329.                 return true;
  330.             }*/
  331.         }
  332.         return false;
  333.     }
  334.    
  335.     public boolean classifica() throws IOException {
  336.         String command = "@classifica,token="+this.token;
  337.         System.out.println(command);
  338.         bufferedWriter.write(command);
  339.         bufferedWriter.newLine();
  340.         bufferedWriter.flush();
  341.         String answer = bufferedReader.readLine();
  342.         if (answer != null) {
  343.             System.out.println("Server response: " + answer);
  344.             /*if (answer.equals("@ok")){
  345.                 return true;
  346.             }*/
  347.         }
  348.         return false;
  349.     }
  350.    
  351.     public boolean uscitaPartita() throws IOException {
  352.         String command = "@uscitaPartita,token="+this.token;
  353.         bufferedWriter.write(command);
  354.         bufferedWriter.newLine();
  355.         bufferedWriter.flush();
  356.         String answer = bufferedReader.readLine();
  357.         if (answer != null) {
  358.             System.out.println("Server response: " + answer);
  359.             if (answer.equals("@ok")){
  360.                 panel.closePanel();
  361.                 return true;
  362.             }
  363.         }
  364.         return false;
  365.     }
  366.    
  367.     public boolean logout() throws IOException {
  368.         String command = "@logout,token="+this.token;
  369.         bufferedWriter.write(command);
  370.         bufferedWriter.newLine();
  371.         bufferedWriter.flush();
  372.         String answer = bufferedReader.readLine();
  373.         if (answer != null) {
  374.             System.out.println("Server response: " + answer);
  375.             if (answer.equals("@ok")){
  376.                 socket.close();
  377.                 System.out.println("client terminated.");
  378.             }
  379.         }
  380.         return false;
  381.     }
  382.    
  383.     public static void main(String[] args) throws UnknownHostException, IOException {
  384.         ClientSocket client = new ClientSocket("localhost", 2011);
  385.         client.start();
  386.         client_sck_srv_handler = new ClientSocketSrvHandler(socket, client);
  387.         client_sck_srv_handler.start();
  388.     }
  389.  
  390. }
  391.  
  392. ##ClientSrvHandler (thread 2)
  393. package game_actions;
  394.  
  395. import java.io.BufferedReader;
  396. import java.io.BufferedWriter;
  397. import java.io.IOException;
  398. import java.io.InputStreamReader;
  399. import java.io.OutputStreamWriter;
  400. import java.net.Socket;
  401.  
  402. import lib.RegExHelper;
  403.  
  404. public class ClientSocketSrvHandler extends Thread {
  405.  
  406.     /**
  407.      * The socket for the connection with the client.
  408.      */
  409.     private Socket socket;
  410.    
  411.     /**
  412.      * The general server
  413.      */
  414.     private ClientSocket client;
  415.    
  416.     /**
  417.      * the token to communicate with the client
  418.      */
  419.     String token;
  420.     //Panel panel = new Panel();
  421.    
  422.     BufferedReader bufferedReader;
  423.     BufferedWriter bufferedWriter;
  424.    
  425.     /**
  426.      * Constructs a ClientHandler that will answer to requests coming through the given socket.
  427.      * @param socket the socket already connected to the client
  428.      * @throws IOException
  429.      */
  430.     public ClientSocketSrvHandler(Socket socket, ClientSocket client) throws IOException {
  431.         this.socket = socket;
  432.         this.client = client;
  433.         bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  434.         //bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
  435.     }
  436.  
  437.     /* (non-Javadoc)
  438.      * @see java.lang.Thread#run()
  439.      */
  440.     public void run() {
  441.         while (true) {
  442.             try {
  443.                 getResponse();
  444.             } catch (InterruptedException e) {
  445.                 // TODO Auto-generated catch block
  446.                 e.printStackTrace();
  447.             } catch (IOException e) {
  448.                 // TODO Auto-generated catch block
  449.                 e.printStackTrace();
  450.             }
  451.         }
  452.     }
  453.    
  454.     public String getResponse() throws InterruptedException, IOException {
  455.         //this.client.wait();
  456.         String response = bufferedReader.readLine();
  457.         if (response == null) {
  458.             System.out.println("Client closed connection.");
  459.         }
  460.         else {
  461.             //this.client.notify();
  462.             return response;
  463.         }
  464.         return "";
  465.     }
  466. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top