SHARE
TWEET

Untitled

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