Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ##some info
- The client operates with request - responses.
- It may also receive broadcast messages from the server so I created a thread that waits for all responses and acts accordingly.
- ##Client Socket (main thread)
- package game_actions;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.util.Scanner;
- import classes.PanelSocket;
- public class ClientSocket extends Thread {
- private String host;
- private int port;
- //private BufferedReader bufferedReader;
- private BufferedWriter bufferedWriter;
- private static Socket socket;
- private String token;
- private PanelSocket panel;
- private static ClientSocketSrvHandler client_sck_srv_handler;
- /**
- * Constructs a client that will connect to a server with the given host and port
- * @param host the IP address for the connection to the server
- * @param port the port for the connection to the server
- * @throws IOException
- * @throws UnknownHostException
- */
- public ClientSocket(String host, int port) throws UnknownHostException, IOException {
- this.host = host;
- this.port = port;
- System.out.println("Connecting to server. Host: " + host + " - port: " + port);
- socket = new Socket(host, port);
- System.out.println("Connected.");
- //bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- bufferedWriter = new BufferedWriter(
- new OutputStreamWriter(socket.getOutputStream()));
- panel = new PanelSocket(this);
- }
- /**
- * Starts the client.
- * @throws UnknownHostException if the IP address could not be determined.
- * @throws InterruptedException if the thread is interrupted while sleeping.
- */
- public void run() {
- /*ClientSocketSrvHandler client_sck_srv_handler = new ClientSocketSrvHandler(socket, this);
- client_sck_srv_handler.start();*/
- Scanner scan = new Scanner(System.in);
- String clientCommand;
- boolean registerLoginLoop = true;
- while(registerLoginLoop){
- System.out.print("Choose action:\n0. close connection\n1. creaUtente\n2. login\n");
- clientCommand = scan.next();
- switch(Integer.parseInt(clientCommand)){
- case 0: try {
- socket.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println("Terminating client.");
- break;
- case 1: try {
- askCreaUtente();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- break;
- case 2:
- try {
- if (askLogin()) {
- registerLoginLoop = false;
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- break;
- default: System.out.print("Please enter a valid choice.\n");
- }
- }
- boolean actionLoop = true;
- while(actionLoop){
- System.out.print("Choose action:\n1. creaRazza\n2. accessoPartita\n3. mappaGenerale\n4. listaGiocatori\n5. classifica\n6. uscitaPartita\n7. logout\n");
- //TODO: molte azioni ritornano boolean - in futuro, forse potrebbero ritornare void
- clientCommand = scan.next();
- /*if (bufferedReader.ready()) {
- String server_msg = bufferedReader.readLine();
- System.out.println("server sent message" + server_msg);
- }*/
- switch(Integer.parseInt(clientCommand)){
- case 1: try {
- askCreaRazza();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } break;
- case 2: try {
- accessoPartita();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } break;
- case 3: try {
- mappaGenerale();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } break;
- case 4: try {
- listaGiocatori();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } break;
- case 5: try {
- classifica();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } break;
- case 6: try {
- uscitaPartita();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } break;
- case 7: try {
- logout();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } break;
- default: System.out.print("Please enter a valid choice.\n");
- }
- }
- }
- public boolean askCreaUtente() throws IOException, InterruptedException {
- Scanner scan = new Scanner(System.in);
- System.out.print("Username:\n");
- String username = scan.next();
- System.out.print("Password:\n");
- String password = scan.next();
- String command = "@creaUtente,user="+username+",pass="+password;
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = client_sck_srv_handler.getResponse();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- if (answer.equals("@ok")){
- return true;
- }
- }
- return false;
- }
- public boolean askLogin() throws IOException, InterruptedException {
- Scanner scan = new Scanner(System.in);
- System.out.print("Username:\n");
- String username = scan.next();
- System.out.print("Password:\n");
- String password = scan.next();
- String command = "@login,user="+username+",pass="+password;
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = client_sck_srv_handler.getResponse();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- if (answer.startsWith("@ok")){
- //save the token
- String[] splitted = answer.split(",");
- this.token = splitted[1];
- System.out.println("token received: " + this.token);
- return true;
- }
- }
- return false;
- }
- public boolean askCreaRazza() throws IOException {
- Scanner scan = new Scanner(System.in);
- System.out.print("Species Name:\n");
- String species_name = scan.next();
- System.out.print("Species Type (c or e):\n");
- String species_type = scan.next();
- String command = "@creaRazza,token="+this.token+",nome="+species_name+",tipo="+species_type;
- System.out.println("command: "+command);
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- /*if (answer.equals("@ok")){
- return true;
- }*/
- }
- return false;
- }
- public boolean accessoPartita() throws IOException {
- String command = "@accessoPartita,token="+this.token;
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- /*if (answer.equals("@ok")){
- return true;
- }*/
- }
- return false;
- }
- public boolean mappaGenerale() throws IOException {
- String command = "@mappaGenerale,token="+this.token;
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- if (answer.startsWith("@mappaGenerale")){
- System.out.println("Rendering map...");
- String[] mappa = answer.split("},");
- String mappachars = mappa[1];
- /*mappachars = mappachars.replaceAll("(\\[)", "");
- mappachars = mappachars.replaceAll("(\\])", "");*/
- panel.showPanel(mappachars);
- }
- }
- return false;
- }
- public boolean muoviDinosauro(String id_dino, String dest) throws IOException { //TODO cambiare string dest - forse ritorno da cambiare in String o simile
- String command = "@muoviDinosauro,token="+this.token+",idDino="+id_dino+",dest="+dest;
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- if (answer.startsWith("@ok")){
- //movimento possibile - spostare dinosauro panel
- }
- else
- if (answer.startsWith("@combattimento")){
- //battle! - eliminare dinosauro perdente dalla mappa
- }
- else
- return false;
- }
- return false;
- }
- public String vistaLocale(String dino_id) throws IOException {
- String command = "@vistaLocale,token="+this.token+",idDino="+dino_id;
- System.out.println(command);
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- return answer;
- }
- return null;
- }
- public String listaDinosauri() throws IOException {
- String command = "@listaDinosauri,token="+this.token;
- System.out.println(command);
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- return answer;
- }
- return null;
- }
- public String statoDinosauro(String dino_id) throws IOException {
- String command = "@statoDinosauro,token="+this.token+",idDino="+dino_id;
- System.out.println(command);
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- return answer;
- }
- return null;
- }
- public boolean listaGiocatori() throws IOException {
- String command = "@listaGiocatori,token="+this.token;
- System.out.println(command);
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- /*if (answer.equals("@ok")){
- return true;
- }*/
- }
- return false;
- }
- public boolean classifica() throws IOException {
- String command = "@classifica,token="+this.token;
- System.out.println(command);
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- /*if (answer.equals("@ok")){
- return true;
- }*/
- }
- return false;
- }
- public boolean uscitaPartita() throws IOException {
- String command = "@uscitaPartita,token="+this.token;
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- if (answer.equals("@ok")){
- panel.closePanel();
- return true;
- }
- }
- return false;
- }
- public boolean logout() throws IOException {
- String command = "@logout,token="+this.token;
- bufferedWriter.write(command);
- bufferedWriter.newLine();
- bufferedWriter.flush();
- String answer = bufferedReader.readLine();
- if (answer != null) {
- System.out.println("Server response: " + answer);
- if (answer.equals("@ok")){
- socket.close();
- System.out.println("client terminated.");
- }
- }
- return false;
- }
- public static void main(String[] args) throws UnknownHostException, IOException {
- ClientSocket client = new ClientSocket("localhost", 2011);
- client.start();
- client_sck_srv_handler = new ClientSocketSrvHandler(socket, client);
- client_sck_srv_handler.start();
- }
- }
- ##ClientSrvHandler (thread 2)
- package game_actions;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.net.Socket;
- import lib.RegExHelper;
- public class ClientSocketSrvHandler extends Thread {
- /**
- * The socket for the connection with the client.
- */
- private Socket socket;
- /**
- * The general server
- */
- private ClientSocket client;
- /**
- * the token to communicate with the client
- */
- String token;
- //Panel panel = new Panel();
- BufferedReader bufferedReader;
- BufferedWriter bufferedWriter;
- /**
- * Constructs a ClientHandler that will answer to requests coming through the given socket.
- * @param socket the socket already connected to the client
- * @throws IOException
- */
- public ClientSocketSrvHandler(Socket socket, ClientSocket client) throws IOException {
- this.socket = socket;
- this.client = client;
- bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
- //bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
- }
- /* (non-Javadoc)
- * @see java.lang.Thread#run()
- */
- public void run() {
- while (true) {
- try {
- getResponse();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- public String getResponse() throws InterruptedException, IOException {
- //this.client.wait();
- String response = bufferedReader.readLine();
- if (response == null) {
- System.out.println("Client closed connection.");
- }
- else {
- //this.client.notify();
- return response;
- }
- return "";
- }
- }
Add Comment
Please, Sign In to add comment