From b2d725f4c3ada6717f8b82c9c686a44114b154ff Mon Sep 17 00:00:00 2001 From: Sebastian Lenzlinger Date: Sat, 26 Mar 2022 13:14:36 +0100 Subject: [PATCH] Finnished ClientMsgDecoder! last thing todo is implement the execution of the input. --- ...dmi.dbis.cs108.example.HelloWorldTest.html | 6 +- .../dbis/cs108/multiplayer/client/Client.java | 248 +++++++++--------- .../client/InputToProtocolMap.java | 40 +-- .../client/NTtBProtocolParser.java | 110 ++++---- .../multiplayer/client/ProtocolParser.java | 15 +- .../multiplayer/protocol/NTtBFormatMsg.java | 66 +++-- .../protocol/NTtB_Protocol_Definition.txt | 2 + .../protocol/NightTrainProtocol.java | 4 +- .../multiplayer/server/ClientHandler.java | 37 ++- .../multiplayer/server/ClientMsgDecoder.java | 126 +++++---- .../server/cmd/methods/CommandExecuter.java | 73 ++++++ .../server/cmd/methods/msgToMethod.java | 8 + 12 files changed, 423 insertions(+), 312 deletions(-) create mode 100644 src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/cmd/methods/CommandExecuter.java create mode 100644 src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/cmd/methods/msgToMethod.java diff --git a/build/reports/tests/test/classes/ch.unibas.dmi.dbis.cs108.example.HelloWorldTest.html b/build/reports/tests/test/classes/ch.unibas.dmi.dbis.cs108.example.HelloWorldTest.html index ad548b2..4b6b755 100644 --- a/build/reports/tests/test/classes/ch.unibas.dmi.dbis.cs108.example.HelloWorldTest.html +++ b/build/reports/tests/test/classes/ch.unibas.dmi.dbis.cs108.example.HelloWorldTest.html @@ -41,7 +41,7 @@
-
0.009s
+
0.013s

duration

@@ -76,7 +76,7 @@ testMain() -0.009s +0.013s passed @@ -89,7 +89,7 @@ Generated by -Gradle 6.9.2 at 06.03.2022, 13:30:14

+Gradle 6.9.2 at 26.03.2022, 12:19:23

diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/Client.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/Client.java index 0b3c318..3aa6a19 100644 --- a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/Client.java +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/Client.java @@ -9,140 +9,142 @@ import java.util.Scanner; public class Client { - private Socket socket; - private BufferedReader in; - private BufferedWriter out; - public String userName; + private Socket socket; + private BufferedReader in; + private BufferedWriter out; + public String userName; - public Client(Socket socket, String userName) { + public Client(Socket socket, String userName) { + try { + this.socket = socket; + this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); + this.in = new BufferedReader((new InputStreamReader((socket.getInputStream())))); + + //TODO add the system based generated username here. + //TODO hide connecting logik(next 4 lines) + this.userName = userName; + this.out.write(getUsername()); + this.out.newLine(); + this.out.flush(); + } catch (IOException e) { + e.printStackTrace(); + closeEverything(socket, in, out); + } + } + + public void sendMessage() { + try { + Scanner sc = new Scanner(System.in); + while (socket.isConnected()) { + String msg = sc.nextLine(); + String encodedMsg = ""; try { - this.socket = socket; - this.out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); - this.in = new BufferedReader((new InputStreamReader((socket.getInputStream())))); - - //TODO add the system based generated username here. - //TODO hide connecting logik(next 4 lines) - this.userName = userName; - this.out.write(getUsername()); - this.out.newLine(); - this.out.flush(); - } catch (IOException e) { - e.printStackTrace(); - closeEverything(socket, in, out); + encodedMsg = encodeMessage(msg); + } catch (NoLegalProtocolCommandStringFoundException e) { + System.out.println("ERROR: no legal command found"); + encodedMsg = ""; + } catch (EmptyClientInputException e) { + //Maybe this exception shouldn't do anything. + } finally { + out.write(encodedMsg); + out.newLine(); + out.flush(); } + + + } + } catch (IOException e) { + e.printStackTrace(); + closeEverything(socket, in, out); } + } - public void sendMessage() { - try { - Scanner sc = new Scanner(System.in); - while (socket.isConnected()) { - String msg = sc.nextLine(); - String encodedMsg = ""; - try { - encodedMsg = encodeMessage(msg); - } catch (NoLegalProtocolCommandStringFoundException e) { - System.out.println("ERROR: no legal command found"); - encodedMsg = ""; - } catch (EmptyClientInputException e) { - //Maybe this exception shouldn't do anything. - } finally { - out.write(encodedMsg); - out.newLine(); - out.flush(); - } + /** + * Uses NTtBProtocolParser to turn Client input into the NTtB Protocol format. Must + * be called before a client input is sent to the server. + * + * @param msg the msg to be encoded. + * @return Message encoded adhering to the NTtB Protocoll. + */ + private String encodeMessage(String msg) + throws NoLegalProtocolCommandStringFoundException, EmptyClientInputException { + NTtBProtocolParser pp = new NTtBProtocolParser(this); + return pp.parseMsg(msg); + } + //TODO implement decoding of server input + private String decodeServerMsg(String msg){return null;} - - } - } catch (IOException e) { - e.printStackTrace(); - closeEverything(socket, in, out); - } - } - - /** - * Uses NTtBProtocolParser to turn Client - * input into the NTtB Protocol format. - * Must be called before a client input is sent to the server. - * @param msg the msg to be encoded. - * @return Message encoded adhering to the NTtB Protocoll. - */ - private String encodeMessage(String msg) throws NoLegalProtocolCommandStringFoundException, EmptyClientInputException { - NTtBProtocolParser pp = new NTtBProtocolParser(this); - return pp.parseMsg(msg); - } - - /** - * Listens for incoming messages - */ - public void chatListener() { + /** + * Listens for incoming messages + */ + public void chatListener() { /*TODO: what type of decoding has to be done - think better about structure for incoming messages - */ - //TODO how shall input be logged? - new Thread(new Runnable() { - @Override - public void run() { - String chatMsg; + TODO how shall input be logged? + */ + new Thread(new Runnable() { + @Override + public void run() { + String chatMsg; - while(socket.isConnected()) { - try { - chatMsg = in.readLine(); - System.out.println(chatMsg); - } catch (IOException e) { - e.printStackTrace(); - closeEverything(socket, in, out); - } - - } - } - }).start(); - } - - public void closeEverything(Socket socket, BufferedReader in, BufferedWriter out) { - //TODO Correctly closing a clients connection - //TODO the server should be notified in a way so he can handle it cleanly - try { - if (in != null) { - in.close(); - } - if (out != null) { - out.close(); - } - if (socket != null) { - socket.close(); - } - } catch (IOException e) { + while (socket.isConnected()) { + try { + chatMsg = in.readLine(); + System.out.println(chatMsg); + } catch (IOException e) { e.printStackTrace(); + closeEverything(socket, in, out); + } + } + } + }).start(); + } + + public void closeEverything(Socket socket, BufferedReader in, BufferedWriter out) { + //TODO Correctly closing a clients connection + //TODO the server should be notified in a way so he can handle it cleanly + try { + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + if (socket != null) { + socket.close(); + } + } catch (IOException e) { + e.printStackTrace(); + } + } + + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + String hostname; + int port = 42069; //can be set via argument later if needed. + if (args.length < 1) { + System.out.println("Enter the host's IP address (or type localhost)"); + hostname = sc.next(); + } else { + hostname = args[0]; + } + System.out.println("Choose a nickname: "); + String username = sc.next(); + Socket socket; + try { + socket = new Socket(hostname, 42069); + Client client = new Client(socket, username); + client.chatListener(); + client.sendMessage(); + } catch (UnknownHostException e) { + System.out.println("Invalid host IP"); + } catch (IOException e) { + e.printStackTrace(); } - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - String hostname; - int port = 42069; //can be set via argument later if needed. - if (args.length < 1) { - System.out.println("Enter the host's IP address (or type localhost)"); - hostname = sc.next(); - } else { - hostname = args[0]; - } - System.out.println("Choose a nickname: "); - String username = sc.next(); - Socket socket; - try { - socket = new Socket(hostname, 42069); - Client client = new Client(socket, username); - client.chatListener(); - client.sendMessage(); - } catch (UnknownHostException e) { - System.out.println("Invalid host IP"); - } catch (IOException e) { - e.printStackTrace(); - } + } - } - - public String getUsername() { - return userName; - } + public String getUsername() { + return userName; + } } diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/InputToProtocolMap.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/InputToProtocolMap.java index 6c70052..9cdddd0 100644 --- a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/InputToProtocolMap.java +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/InputToProtocolMap.java @@ -8,29 +8,29 @@ import java.util.HashSet; public class InputToProtocolMap { - private static final HashMap encoding; - private static final HashSet legalClientInput; + private static final HashMap encoding; + private static final HashSet legalClientInput; - static { - //First add all legal commands to a map - HashMap builder = new HashMap<>(); - builder.put("chat", NightTrainProtocol.NTtBCommands.CHATA); - builder.put("cn", NightTrainProtocol.NTtBCommands.CUSRN); - builder.put("list", NightTrainProtocol.NTtBCommands.LISTP); - builder.put("exit", NightTrainProtocol.NTtBCommands.LEAVG); - //TODO extend according to extended function - //Initialize static final map and set - legalClientInput = new HashSet<>(builder.keySet()); - encoding = new HashMap<>(builder); - } + static { + //First add all legal commands to a map + HashMap builder = new HashMap<>(); + builder.put("chat", NightTrainProtocol.NTtBCommands.CHATA); + builder.put("cn", NightTrainProtocol.NTtBCommands.CUSRN); + builder.put("list", NightTrainProtocol.NTtBCommands.LISTP); + builder.put("exit", NightTrainProtocol.NTtBCommands.LEAVG); + //TODO extend according to extended function + //Initialize static final map and set + legalClientInput = new HashSet<>(builder.keySet()); + encoding = new HashMap<>(builder); + } - public static String encode(String toEncode) throws NoLegalProtocolCommandStringFoundException { - if (legalClientInput.contains(toEncode)) { - return encoding.get(toEncode).toString(); - } else { - throw new NoLegalProtocolCommandStringFoundException(); - } + public static String encode(String toEncode) throws NoLegalProtocolCommandStringFoundException { + if (legalClientInput.contains(toEncode)) { + return encoding.get(toEncode).toString(); + } else { + throw new NoLegalProtocolCommandStringFoundException(); } + } } diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/NTtBProtocolParser.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/NTtBProtocolParser.java index f460e02..3fd7737 100644 --- a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/NTtBProtocolParser.java +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/NTtBProtocolParser.java @@ -6,70 +6,72 @@ import java.util.ArrayList; import java.util.Scanner; /** - * Implements a protocol parser for the NTtB protocoll, - * that transforms client input - * into a server readable format. + * Implements a protocol parser for the NTtB protocoll, that transforms client input into a server + * readable format. */ public class NTtBProtocolParser implements ProtocolParser { - //TODO Possibly bad name, rename to clientMsgParser? - public final Client caller; - public static InputToProtocolMap legalCommands = new InputToProtocolMap(); + + //TODO Possibly bad name, rename to clientMsgParser? + public final Client caller; + public static InputToProtocolMap legalCommands = new InputToProtocolMap(); - public NTtBProtocolParser(Client caller) { - this.caller = caller; - } - @Override - public String parseMsg(String msg) throws NoLegalProtocolCommandStringFoundException, EmptyClientInputException{ - Scanner sc = new Scanner(msg); - ArrayList input = new ArrayList<>(); - String parsedMsg = buildProtocolMsg(input); + public NTtBProtocolParser(Client caller) { + this.caller = caller; + } - while(sc.hasNext()){ - input.add(sc.next()); - } + @Override + public String parseMsg(String msg) + throws NoLegalProtocolCommandStringFoundException, EmptyClientInputException { + Scanner sc = new Scanner(msg); + ArrayList input = new ArrayList<>(); + String parsedMsg = buildProtocolMsg(input); - return parsedMsg; + while (sc.hasNext()) { + input.add(sc.next()); } + return parsedMsg; + } - private String buildProtocolMsg(ArrayList input) throws EmptyClientInputException, NoLegalProtocolCommandStringFoundException { - //TODO - if(emptyClientInput(input)){ - throw new EmptyClientInputException(caller); - } - StringBuilder s = new StringBuilder(); //friendly little helper - s.append(legalCommands.encode(input.get(0))); - if (containsParameters(input)) { - int size = input.size(); - for(int i = 1; i < size; i++) { - s.append("$"); - s.append(input.get(i).toLowerCase()); //parameters are always lower case (is that good?) - } - } - return s.toString(); - } - /** - * Checks if input has parameters - * - * if the list size is smaller than 2, i.e. - * not larger than 1, the input only contains - * a command. - * - * @param input the tokenized input string. - * @return true if input list is larger than 2. - */ - private boolean containsParameters(ArrayList input) { - return input.size() > 1; + private String buildProtocolMsg(ArrayList input) + throws EmptyClientInputException, NoLegalProtocolCommandStringFoundException { + //TODO + if (emptyClientInput(input)) { + throw new EmptyClientInputException(caller); } + StringBuilder s = new StringBuilder(); //friendly little helper + s.append(legalCommands.encode(input.get(0))); + if (containsParameters(input)) { + int size = input.size(); + for (int i = 1; i < size; i++) { + s.append("$"); + s.append(input.get(i).toLowerCase()); //parameters are always lower case (is that good?) + } + } + return s.toString(); + } - /** - * checks if client input is empty - * @param clientInput the clients input. - * @return true if client didn't send any input besides whitespace - */ - private boolean emptyClientInput(ArrayList clientInput) { - return clientInput.isEmpty(); - } + /** + * Checks if input has parameters + *

+ * if the list size is smaller than 2, i.e. not larger than 1, the input only contains a command. + * + * @param input the tokenized input string. + * @return true if input list is larger than 2. + */ + private boolean containsParameters(ArrayList input) { + return input.size() > 1; + } + + /** + * checks if client input is empty + * + * @param clientInput the clients input. + * @return true if client didn't send any input besides whitespace + */ + private boolean emptyClientInput(ArrayList clientInput) { + return clientInput.isEmpty(); + } } diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/ProtocolParser.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/ProtocolParser.java index 6852247..6787bad 100644 --- a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/ProtocolParser.java +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/client/ProtocolParser.java @@ -1,11 +1,12 @@ package ch.unibas.dmi.dbis.cs108.multiplayer.client; public interface ProtocolParser { - /** - * Takes a String from client input and parses into - * server readable message. - * @param msg the message to be parsed - * @return a String message formatted for the specific protocol - */ - String parseMsg(String msg) throws Exception; + + /** + * Takes a String from client input and parses into server readable message. + * + * @param msg the message to be parsed + * @return a String message formatted for the specific protocol + */ + String parseMsg(String msg) throws Exception; } diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NTtBFormatMsg.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NTtBFormatMsg.java index 71a91fe..f06df05 100644 --- a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NTtBFormatMsg.java +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NTtBFormatMsg.java @@ -4,49 +4,47 @@ import java.util.LinkedList; import java.util.Queue; /** - * This class defines what type the ClientMsgDecoder returns after decoding the message. - * This is done so the output can be split into a response to the client and action - * in to the game logik. - * commands should map to methods(maybe classes) - * parameters map to method parameters - * + * This class defines what type the ClientMsgDecoder returns after decoding the message. This is + * done so the output can be split into a response to the client and action in to the game logik. + * commands should map to methods(maybe classes) parameters map to method parameters */ public class NTtBFormatMsg { - private String msgToClient; - private NightTrainProtocol.NTtBCommands command; - private final Queue parameters; //TODO maybe use array? + private String msgToClient; + private NightTrainProtocol.NTtBCommands command; + private final String[] parameters; //TODO maybe use array? - public NTtBFormatMsg(String msgToClient, NightTrainProtocol.NTtBCommands command, Queue parameters) { - this.msgToClient = msgToClient; - this.command = command; - this.parameters = parameters; - } + public NTtBFormatMsg(String msgToClient, NightTrainProtocol.NTtBCommands command, + String[] parameters) { + this.msgToClient = msgToClient; + this.command = command; + this.parameters = parameters; + } - public NTtBFormatMsg() { - this.msgToClient = ""; - this.command = null; - this.parameters = new LinkedList<>(); - } + public NTtBFormatMsg() { + this.msgToClient = ""; + this.command = null; + this.parameters = new String[]{""}; + } - public String getMessage() { - return msgToClient; - } + public String getMessage() { + return msgToClient; + } - public NightTrainProtocol.NTtBCommands getCommand() { - return command; - } + public NightTrainProtocol.NTtBCommands getCommand() { + return command; + } - public Queue getParameters() { - return parameters; - } + public String[] getParameters() { + return parameters; + } - public void setMsgToClient(String msgToClient) { - this.msgToClient = msgToClient; - } + protected void setMsgToClient(String msgToClient) { + this.msgToClient = msgToClient; + } - public void setCommand(NightTrainProtocol.NTtBCommands command) { - this.command = command; - } + protected void setCommand(NightTrainProtocol.NTtBCommands command) { + this.command = command; + } } diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NTtB_Protocol_Definition.txt b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NTtB_Protocol_Definition.txt index 95d2a20..d74795a 100644 --- a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NTtB_Protocol_Definition.txt +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NTtB_Protocol_Definition.txt @@ -10,9 +10,11 @@ * VOTEH: humans voting whos the ghost * QUITS: quit server/ leave servr * LISTP: list players/clients in session with the Server + * CPING: Ping from client to server. */ /** Server Commands: * MSGRS: "Message recieved": Paramaters: a string detailing to the client that and what the server recieved as command. * SEROR: Server had an error. (used for debugging) + * SPING: Ping from server to client; */ \ No newline at end of file diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NightTrainProtocol.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NightTrainProtocol.java index 1a49d12..54b4335 100644 --- a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NightTrainProtocol.java +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/protocol/NightTrainProtocol.java @@ -19,9 +19,9 @@ public class NightTrainProtocol { public enum NTtBCommands { //Client Commands - CRTGM, CHATA, CHATW, CHATG, LEAVG, JOING, VOTEG, QUITS, LISTP, CUSRN, + CRTGM, CHATA, CHATW, CHATG, LEAVG, JOING, VOTEG, QUITS, LISTP, CUSRN,CPING, //Server Responses - MSGRS, SEROR; + MSGRS, SEROR, SPING; } private static HashMap initializeMapping(){ diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/ClientHandler.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/ClientHandler.java index 3e7f95f..773b530 100644 --- a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/ClientHandler.java +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/ClientHandler.java @@ -1,5 +1,6 @@ package ch.unibas.dmi.dbis.cs108.multiplayer.server; +import ch.unibas.dmi.dbis.cs108.multiplayer.protocol.NTtBFormatMsg; import java.io.*; import java.net.Socket; import java.util.HashSet; @@ -12,7 +13,7 @@ public class ClientHandler implements Runnable { private Socket socket; Scanner sc; public static HashSet connectedClients = new HashSet<>(); - public static HashSet inGameClients = new HashSet<>(); + public static HashSet lobby = new HashSet<>(); public static HashSet ghostClients = new HashSet<>(); private ClientMsgDecoder clientMsgDecoder = new ClientMsgDecoder(); @@ -35,19 +36,47 @@ public class ClientHandler implements Runnable { } } + //Getters: + public BufferedWriter getOut() { + return out; + } + + public BufferedReader getIn() { + return in; + } + + public static HashSet getConnectedClients() { + return connectedClients; + } + + public static HashSet getLobby() { + return lobby; + } + + public static HashSet getGhostClients() { + return ghostClients; + } + + public ClientMsgDecoder getClientMsgDecoder() { + return clientMsgDecoder; + } + + //Setters + + @Override /** * point of contact for client and server. */ public void run() { String msg; - String response; + NTtBFormatMsg response; while(socket.isConnected()) { try { msg = in.readLine(); - response = clientMsgDecoder.decodeMsg(msg).getMessage(); //The response of the server to the clients message - out.write(response); + response = clientMsgDecoder.decodeMsg(msg); //The response of the server to the clients message + out.write(response.getMessage()); out.newLine(); out.flush(); //TODO if merely an acknowledgement is sent back to the client, how does the client recieve game updates? diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/ClientMsgDecoder.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/ClientMsgDecoder.java index 0baa43f..9c107ff 100644 --- a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/ClientMsgDecoder.java +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/ClientMsgDecoder.java @@ -6,78 +6,74 @@ import ch.unibas.dmi.dbis.cs108.multiplayer.protocol.NoLegalProtocolCommandStrin import ch.unibas.dmi.dbis.cs108.multiplayer.protocol.ProtocolDecoder; import java.util.LinkedList; -import java.util.List; import java.util.Queue; public class ClientMsgDecoder implements ProtocolDecoder { - private NightTrainProtocol protocol; - @Override - //TODO this method IS NOT FINNISHED. @return is not correct as of now! - public NTtBFormatMsg decodeMsg(String msg) { - List msgTokens = tokenizeMsg(msg); //List where we'll put the string tokens seperated by $. - String cmd; //The command token - NightTrainProtocol.NTtBCommands cmdObject; - Queue parameters; - NTtBFormatMsg util = new NTtBFormatMsg(); - cmd = serverResponseBuilder(msgTokens); - cmdObject = getCommandConstant(cmd); - util.setCommand(cmdObject); - try{ - cmd = getCommandStringToken(msgTokens); - } catch (NoCommandTokenException e) { - //TODO: decide what to do here. How can we catch this smartly and where do we send it? - System.out.println(("ClientMsgDecoder cannot find a command token")); - e.printStackTrace(System.out); - return new NTtBFormatMsg("ERROR$NoCommandTokenException caught!", null, null); - } + private NightTrainProtocol protocol; - return null; + @Override + //TODO this method IS NOT FINNISHED. @return is not correct as of now! + public NTtBFormatMsg decodeMsg(String msg) { + //Declare needed variables + String[] msgTokens; //List where we'll put the string tokens seperated by $. + String ackMsg; //The command token + String[] parameters; + NightTrainProtocol.NTtBCommands cmdObject; + //Initalize fields for return object + msgTokens = tokenizeMsg(msg); + ackMsg = serverResponseBuilder(msgTokens); + parameters = new String[msgTokens.length-1]; + cmdObject = getCommandConstant(msgTokens[0]); + return new NTtBFormatMsg(ackMsg, cmdObject, parameters); + } + + /* + * Builds the servers response message + * to client + */ + private String serverResponseBuilder(String[] msgTokens) { + StringBuilder sb = new StringBuilder(); + //assumes not empty list! + NightTrainProtocol.NTtBCommands cmd = getCommandConstant(msgTokens[0]); + sb.append("SERVER: "); + sb.append("Command *" + cmd.toString() + "* recieved!"); + + return sb.toString(); + } + + //Uses the NightTrainProtocol classes utility method + private boolean isLegalCmdString(String cmd) { + return protocol.isLegalCmdString(cmd); + } + + private String getCommandStringToken(String[] msgTokens) throws NoCommandTokenException { + return msgTokens[0]; + } + + private NightTrainProtocol.NTtBCommands getCommandConstant(String stringToken) { + try { + return protocol.getCmdEnumObject(stringToken); + } catch (NoLegalProtocolCommandStringFoundException e) { + e.printStackTrace(); + e.getMessage(); + } finally { + return NightTrainProtocol.NTtBCommands.SEROR; } - /* - * Builds the servers response message - * to client - */ - private String serverResponseBuilder(List msgTokens){ - StringBuilder sb = new StringBuilder(); - //assumes not empty list! - NightTrainProtocol.NTtBCommands cmd = getCommandConstant(msgTokens.get(0)); - sb.append("SERVER: "); - sb.append("Command *" + cmd.toString() + "* recieved!"); + } - return sb.toString(); - } + //Creates tokens from the clientMsg and puts them in a list + //TODO what side effects could be here? + private String[] tokenizeMsg(String msg) { + return msg.split("$"); + } - //Uses the NightTrainProtocol classes utility method - private boolean isLegalCmdString(String cmd) { - return protocol.isLegalCmdString(cmd); - } - private String getCommandStringToken(List msgTokens) throws NoCommandTokenException { - return msgTokens.get(0); - } - private NightTrainProtocol.NTtBCommands getCommandConstant(String stringToken) { - try{ - return protocol.getCmdEnumObject(stringToken); - }catch (NoLegalProtocolCommandStringFoundException e) { - e.printStackTrace(); - e.getMessage(); - } finally { - return NightTrainProtocol.NTtBCommands.SEROR; - } - - } - - //Creates tokens from the clientMsg and puts them in a list - private List tokenizeMsg(String msg) { - return null; - } - - /* - * This method should implement the initiation - * of server agency according to client msg - */ - private Queue serverActionBuilder() { - return new LinkedList(); - } + /* + * This method should implement the initiation + * of server agency according to client msg + */ + private Queue serverActionBuilder() { + return new LinkedList(); + } } diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/cmd/methods/CommandExecuter.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/cmd/methods/CommandExecuter.java new file mode 100644 index 0000000..78533a5 --- /dev/null +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/cmd/methods/CommandExecuter.java @@ -0,0 +1,73 @@ +package ch.unibas.dmi.dbis.cs108.multiplayer.server.cmd.methods; + +import ch.unibas.dmi.dbis.cs108.multiplayer.protocol.NTtBFormatMsg; +import ch.unibas.dmi.dbis.cs108.multiplayer.server.ClientHandler; +import java.io.IOException; + +/** + * This Class implements actually acting on the clients + * messages. + */ +public class CommandExecuter { + + ClientHandler caller; + + public static void execute(NTtBFormatMsg msg) { + switch (msg.getCommand()) { + case CRTGM: + break; + case CHATA: + broadcastClientMsg(msg.getParameters()); + break; + case CHATG: + //TODO + break; + case LEAVG: + //TODO + break; + case JOING: + //TODO + break; + case VOTEG: + //TODO + break; + case QUITS: + quitServer(); + break; + case CHATW: + wisper(msg.getParameters()); + break; + case LISTP: + //TODO + break; + case CUSRN: + changeNickname(msg.getParameters()); + break; + case CPING: + pongS(); + break; + case MSGRS: + //TODO + break; + case SEROR: + //TODO + break; + case SPING: + pongC(); + break; + } + } + + /** + * boradcast chat message to everyone + * @param parameters should only have one entry i.e. + * parameters.length == 1 + * should be true; + */ + private static void broadcastClientMsg(String[] parameters) throws IOException { + for(ClientHandler clients: ClientHandler.connectedClients) { + clients.getOut().write(parameters[0]); + } + } + +} diff --git a/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/cmd/methods/msgToMethod.java b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/cmd/methods/msgToMethod.java new file mode 100644 index 0000000..4e834da --- /dev/null +++ b/src/main/java/ch/unibas/dmi/dbis/cs108/multiplayer/server/cmd/methods/msgToMethod.java @@ -0,0 +1,8 @@ +package ch.unibas.dmi.dbis.cs108.multiplayer.server.cmd.methods; + +public interface msgToMethod { + + void quit(); + + +}