From 5e61d4ec97ee18ea09200480a6a01a52e17dd62f Mon Sep 17 00:00:00 2001 From: Jonas Gohn Date: Mon, 5 Mar 2018 15:39:07 +0100 Subject: [PATCH 1/7] initial commit --- Class1/Client.java | 27 --- Class1/Client/.gitignore | 1 + Class1/Client/src/main/java/Client.java | 67 ++++++++ Class1/Client/src/main/java/FileIO.java | 39 +++++ Class1/Client/src/main/java/Main.java | 138 +++++++++++++++ .../Client/src/main/resources/numberfile.txt | 2 + Class1/Exercises/README.md | 53 ------ Class1/Server.java | 26 --- Class1/Server/.gitignore | 1 + Class1/Server/src/main/java/Client.java | 64 +++++++ Class1/Server/src/main/java/FileIO.java | 41 +++++ Class1/Server/src/main/java/Main.java | 135 +++++++++++++++ .../Server/src/main/java/NameCollector.java | 32 ++++ Class1/Server/src/main/java/Server.java | 159 ++++++++++++++++++ Class1/Server/src/main/java/Util.java | 9 + .../Server/src/main/resources/serverfile.txt | 3 + 16 files changed, 691 insertions(+), 106 deletions(-) delete mode 100644 Class1/Client.java create mode 100755 Class1/Client/.gitignore create mode 100755 Class1/Client/src/main/java/Client.java create mode 100755 Class1/Client/src/main/java/FileIO.java create mode 100755 Class1/Client/src/main/java/Main.java create mode 100755 Class1/Client/src/main/resources/numberfile.txt delete mode 100644 Class1/Exercises/README.md delete mode 100644 Class1/Server.java create mode 100755 Class1/Server/.gitignore create mode 100755 Class1/Server/src/main/java/Client.java create mode 100755 Class1/Server/src/main/java/FileIO.java create mode 100755 Class1/Server/src/main/java/Main.java create mode 100755 Class1/Server/src/main/java/NameCollector.java create mode 100755 Class1/Server/src/main/java/Server.java create mode 100755 Class1/Server/src/main/java/Util.java create mode 100755 Class1/Server/src/main/resources/serverfile.txt diff --git a/Class1/Client.java b/Class1/Client.java deleted file mode 100644 index 07f5449..0000000 --- a/Class1/Client.java +++ /dev/null @@ -1,27 +0,0 @@ -import java.util.*; -import java.io.*; -import java.net.*; - -class Client -{ - public static void main(String[] args) - throws Exception - { - int port = 12345; - String computer = "localhost"; - - try ( - Socket s = new Socket(computer, port); - - Scanner sc = new Scanner(s.getInputStream()); - PrintWriter pw = new PrintWriter(s.getOutputStream()); - ) { - pw.println(args[0]); - pw.flush(); - - int textLength = sc.nextInt(); - System.out.println(textLength); - } - - } -} diff --git a/Class1/Client/.gitignore b/Class1/Client/.gitignore new file mode 100755 index 0000000..5241a72 --- /dev/null +++ b/Class1/Client/.gitignore @@ -0,0 +1 @@ +*.class \ No newline at end of file diff --git a/Class1/Client/src/main/java/Client.java b/Class1/Client/src/main/java/Client.java new file mode 100755 index 0000000..68b19cf --- /dev/null +++ b/Class1/Client/src/main/java/Client.java @@ -0,0 +1,67 @@ +package main.java; + +import java.util.*; +import java.util.logging.Logger; +import java.io.*; +import java.net.*; + +class Client { + + private static final String DISC = "DISCONNECT"; + + private Scanner reader; + private PrintWriter writer; + private Socket internalSocket; + + Logger logger = Logger.getLogger(this.getClass().getName()); + + public Client(String hostname, int port) { + try { + internalSocket = new Socket(hostname, port); + reader = new Scanner(internalSocket.getInputStream()); + writer = new PrintWriter(internalSocket.getOutputStream()); + // Dont close socket because will close io streams + } catch (UnknownHostException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void sendMsg(String message) { + logger.info("Sending \"" + message + "\" to server"); + writer.println(message); + writer.flush(); + } + + public String readMsg() { + while (!reader.hasNext()) { + } + String message = reader.nextLine(); + logger.info("Received \"" + message + "\" from server"); + return message; + } + + public void echoFunction(String message) { + // Send msg and get log response + sendMsg(message); + readMsg(); + } + + public void sendMsg(int message) { + logger.info("Sending \"" + message + "\" to server"); + writer.println(message); + writer.flush(); + } + + public void sendDisconnect() { + writer.println(DISC); + writer.flush(); + try { + internalSocket.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + +} diff --git a/Class1/Client/src/main/java/FileIO.java b/Class1/Client/src/main/java/FileIO.java new file mode 100755 index 0000000..d023d3c --- /dev/null +++ b/Class1/Client/src/main/java/FileIO.java @@ -0,0 +1,39 @@ +package main.java; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class FileIO { + + private BufferedReader reader; + + public FileIO(String filename) { + try { + reader = new BufferedReader(new FileReader(filename)); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + } + + List readNumbers() { + String line; + ArrayList list = new ArrayList<>(); + try { + while ((line = reader.readLine()) != null) { + String[] tokens = line.split(","); + for (String token : tokens) { + list.add(Integer.parseInt(token)); + } + + } + } catch (IOException e) { + e.printStackTrace(); + } + return list; + } + +} diff --git a/Class1/Client/src/main/java/Main.java b/Class1/Client/src/main/java/Main.java new file mode 100755 index 0000000..e14b688 --- /dev/null +++ b/Class1/Client/src/main/java/Main.java @@ -0,0 +1,138 @@ +package main.java; + +import java.util.ArrayList; +import java.util.Scanner; + +public class Main { + + public static final String END_TOKEN = "end"; + public static final String EXIT_TOKEN = "exit"; + + public static void main(String[] args) { + boolean usingExtended = false; + boolean connectOnly = false; + boolean giveNumbers = false; + boolean chatMode = false; + String chatname = "Bob"; // default name + int giveRandom = 5; + + if (args.length > 0) { + if (args[0].equals("-2e")) { + usingExtended = true; + } + + if (args[0].equals("-4")) { + connectOnly = true; + } + + if (args[0].equals("-5")) { + giveNumbers = true; + if (args.length > 1) { + giveRandom = Integer.parseInt(args[1]); + } + } + + if (args[0].equals("-6")) { + chatMode = true; + if (args.length > 1) { + chatname = args[1]; + } + } + + } + Client client = new Client("localhost", 12345); + + // Exercise 4 + if (connectOnly) { + System.out.println("Current connection count: " + client.readMsg()); + return; + } + // Exercise 5 + + if (giveNumbers) { + System.out.println("Generating " + giveRandom + " random numbers and sending to server."); + for (int i = 0; i < giveRandom; i++) { + // some number between 0 and 20 + int num = (int) (Math.random() * 21); + client.sendMsg(num); + } + client.sendMsg(EXIT_TOKEN); + return; + } + + // Exercise 6 + + if (chatMode) { + boolean isStopped = false; + client.sendMsg(chatname); + // One thread for reading + new Thread() { + @Override + public void run() { + while (!Thread.currentThread().isInterrupted()) { + String msg = client.readMsg(); + System.out.println("Got message:"); + System.out.println(msg); + } + } + }.start(); + // One thread for writing + new Thread() { + @Override + public void run() { + Scanner sc = new Scanner(System.in); + while (!Thread.currentThread().isInterrupted()) { + String outgoing = sc.nextLine(); + client.sendMsg(outgoing); + System.out.println("Sent message:"); + System.out.println(outgoing); + } + sc.close(); + } + }.start(); + + while (!isStopped) { + try { + System.out.println("Conversation open for 120 seconds."); + Thread.sleep(120000); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + return; + } + + if (!usingExtended) { + // Exercise 0 + client.echoFunction("echo this back"); + // Exercise 1 + client.sendMsg("4"); + String answer = client.readMsg(); + System.out.println(answer); + + } + // Exercise 2 + FileIO fileHandler = new FileIO("main/resources/numberfile.txt"); + ArrayList fileNumbers = (ArrayList) fileHandler.readNumbers(); + + for (int number : fileNumbers) { + client.sendMsg(number); + } + client.sendMsg(END_TOKEN); + + for (int i = 0; i < fileNumbers.size(); i++) { + String recv = client.readMsg(); + System.out.println(recv); + } + + // Exercise 3 + String filename = "serverfile.txt"; + client.sendMsg(filename); + System.out.println(client.readMsg()); + if (usingExtended) { + return; + } + + } + +} diff --git a/Class1/Client/src/main/resources/numberfile.txt b/Class1/Client/src/main/resources/numberfile.txt new file mode 100755 index 0000000..64ea8bc --- /dev/null +++ b/Class1/Client/src/main/resources/numberfile.txt @@ -0,0 +1,2 @@ +1,2,3 +4,5 \ No newline at end of file diff --git a/Class1/Exercises/README.md b/Class1/Exercises/README.md deleted file mode 100644 index 5853bc1..0000000 --- a/Class1/Exercises/README.md +++ /dev/null @@ -1,53 +0,0 @@ -0. Make a server and a client. - Start the server on port 12345. - Establish a client connection to it. - The client should send a textual message on a line to the server. - The server should send the line back, and the client should print it. - -1. The server contains a string in the beginning. - The client should send a number (n) in textual form to the server. - The server should print its string back n times on a line to the client. - The client receives the server'r reply, then prints it on the standard output. - -2. The client reads numbers from a file, and sends them to the server. - After the last number, the client sends the text "end" to the server. - The server applies the function f(n)=2*n+1 to all numbers, - and sends them back to the client. - The client should print the received numbers. - - 1. The same as exercise 2, but after a client has quit, - the server should wait for another connection. - Thus, the server never exits: it is always waiting for a client to connect, - or is communicating with one. - -3. The client sends a filename to the server. - The server tries to open the file. - If the file does not exist, the server replies with an error message. - If the file exists, the server sends the lines of the file to the client. - -4. The server keeps track of the number of clients. - Whenever a client is connected, the server increases this number, - sends it back to the client, - then closes the connection and waits for the next client to come. - -5. The server stores a number, which is initially 0. - After connection, the current client sends some numbers, then the text "exit". - For each number sent, the server adds the number to its internal counter, - and sends the increased value back to the client. - When the client exits, the server starts waiting for the next client. - -6. The server waits for two connections on the same port. - After they both have arrived, they send their names on one line. - After that, they start exchanging messages in the following way. - First, client 1 sends a message to the server, and the server sends this message on to client 2. - Then, client 2 sends a message to the server, and the server sends this message on to client 1. - The clients continue sending their messages in alternate steps. - - 1. First, the server accepts n connections from clients, n being a fixed number. - Once a client appears, he sends his name on a one line message. - After all names have been collected, the server starts the following activity, - and repeats it until infinity. - - The server connects all clients in order, and receives a message from all of them. - When the clients have sent all their lines, - the server sends all messages (along with the name of the sending client) to all clients. diff --git a/Class1/Server.java b/Class1/Server.java deleted file mode 100644 index c3888be..0000000 --- a/Class1/Server.java +++ /dev/null @@ -1,26 +0,0 @@ -import java.util.*; -import java.io.*; -import java.net.*; - -class Server -{ - public static void main(String[] args) - throws Exception - { - int port = 12345; - - try ( - ServerSocket ss = new ServerSocket(port); - Socket s = ss.accept(); - - Scanner sc = new Scanner(s.getInputStream()); - PrintWriter pw = new PrintWriter(s.getOutputStream()); - ) { - - pw.println(text.length()); - pw.flush(); - - } - - } -} diff --git a/Class1/Server/.gitignore b/Class1/Server/.gitignore new file mode 100755 index 0000000..5241a72 --- /dev/null +++ b/Class1/Server/.gitignore @@ -0,0 +1 @@ +*.class \ No newline at end of file diff --git a/Class1/Server/src/main/java/Client.java b/Class1/Server/src/main/java/Client.java new file mode 100755 index 0000000..73f3cb9 --- /dev/null +++ b/Class1/Server/src/main/java/Client.java @@ -0,0 +1,64 @@ +package main.java; + +import java.util.*; +import java.util.logging.Logger; +import java.io.*; +import java.net.*; + +class Client { + + public Logger logger = Logger.getLogger(this.getClass().getName()); + public static final String DISC = "DISCONNECT"; + + private Scanner reader; + private PrintWriter inputPrinter; + + public Client(Socket clientSocket) { + try { + reader = new Scanner(clientSocket.getInputStream()); + inputPrinter = new PrintWriter(clientSocket.getOutputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public String readMsg() { + while (!reader.hasNext()) { + } + String message = reader.nextLine(); + logger.info("Received \"" + message + "\" from client"); + return message; + } + + public void writeMessage(String message) { + logger.info("Sending \"" + message + "\" to client"); + inputPrinter.println(message); + inputPrinter.flush(); + } + + public void writeMessage(int message) { + logger.info("Sending \"" + message + "\" to client"); + inputPrinter.println(message); + inputPrinter.flush(); + } + + public void echoFunction() { + // Receive and send back same msg + String toEcho = readMsg(); + writeMessage(toEcho); + } + + public void sendNtimes(String toPrint, int n) { + String toSend = ""; + for (int i = 0; i < n; i++) { + toSend += toPrint; + } + writeMessage(toSend); + } + + public void closeClient() { + inputPrinter.close(); + reader.close(); + } +} diff --git a/Class1/Server/src/main/java/FileIO.java b/Class1/Server/src/main/java/FileIO.java new file mode 100755 index 0000000..1620d8a --- /dev/null +++ b/Class1/Server/src/main/java/FileIO.java @@ -0,0 +1,41 @@ +package main.java; + +import java.io.BufferedReader; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; + +public class FileIO { + + private BufferedReader reader; + private boolean exists; + + public FileIO(String filename) { + try { + reader = new BufferedReader(new FileReader(filename)); + exists = true; + } catch (FileNotFoundException e) { + System.err.println("ERROR: Cannot find file"); + exists = false; + } + } + + public boolean exists() { + return exists; + } + + public String getFileContent() { + String output = ""; + String line; + + try { + while ((line = reader.readLine()) != null) { + output += line + " "; + } + } catch (IOException e) { + e.printStackTrace(); + } + return output; + } + +} diff --git a/Class1/Server/src/main/java/Main.java b/Class1/Server/src/main/java/Main.java new file mode 100755 index 0000000..3262b06 --- /dev/null +++ b/Class1/Server/src/main/java/Main.java @@ -0,0 +1,135 @@ +package main.java; + +import java.util.ArrayList; + +public class Main { + + public static final String END_TOKEN = "end"; + public static final int CLIENT_COUNTER = 5; + + public static void main(String[] args) { + boolean extendedVersion = false; + String tmp = ""; + if (args.length > 0) { + if (args[0].equals("-2e")) { + extendedVersion = true; + } + } + + Server server = new Server(12345); + server.acceptClient(); + + Client client = server.getClient(0); + + if (!extendedVersion) { + String manyPrints = "ThisManyTimes"; + + // Exercise 0 + client.echoFunction(); + // Exercise 1 + tmp = client.readMsg(); + int n = Integer.parseInt(tmp); + client.sendNtimes(manyPrints, n); + } + // Exercise 2 + // For infinite clients set extendedVersion to true + + boolean happened = false; + + while (extendedVersion || !happened) { + if (extendedVersion && server.getClientCount() < 1) { + server.acceptClient(); + client = server.getClient(0); + } + + ArrayList numbersToHandle = new ArrayList<>(); + + while (!(tmp = client.readMsg()).equals(END_TOKEN)) { + try { + numbersToHandle.add(Integer.parseInt(tmp)); + } catch (NumberFormatException e) { + System.err.println("ERROR: expected integer"); + } + } + + for (int num : numbersToHandle) { + int tmpNumber = Util.numberFunction(num); + client.writeMessage(tmpNumber); + } + + if (extendedVersion) { + server.removeClient(client); + } else { + happened = true; + } + } + // Exercise 3 + String filename = client.readMsg(); + FileIO serverFile = new FileIO("main/resources/" + filename); + if (serverFile.exists()) { + String toSend = serverFile.getFileContent(); + client.writeMessage(toSend); + } else { + client.writeMessage("ERROR: Could not find file"); + } + + // Exercise 4 + // Removing all clients before initiating exercise 4 + if (server.getClientCount() != 1) { + System.out.println("Only expecting one client online at this time"); + + return; + } else { + server.removeClient(server.getClient(0)); + } + + while (server.totalConnections < CLIENT_COUNTER) { + server.acceptClient(); + // This returns newest client in queue + Client newestClient = server.getClient(server.getClientCount() - 1); + newestClient.writeMessage(server.totalConnections); + server.removeClient(newestClient); + } + + // Exercise 5 + // Assuming no active connection at this time + assert (server.getClientCount() == 0); + while (server.getSum() < 100) { + server.acceptClient(); + client = server.getClient(0); + String number; + while (!(number = client.readMsg()).equals("exit")) { + server.addToInternal(number); + } + server.removeClient(client); + System.out.println("Current sum : " + server.getSum()); + } + + // Exercise 6 + while (server.getClientCount() < 2) { + server.acceptClient(); + } + Client first = server.getClient(0); + Client second = server.getClient(1); + String nameFirst; + String nameSecond; + NameCollector nameCollectorFirst = new NameCollector(first); + NameCollector nameCollectorSecond = new NameCollector(second); + + Thread t1 = new Thread(nameCollectorFirst); + Thread t2 = new Thread(nameCollectorSecond); + t1.start(); + t2.start(); + try { + t1.join(); + t2.join(); + } catch (InterruptedException e) { + e.printStackTrace(); + } + // Application will wait until both threads have collected name from client + + System.out.println("First name: " + nameCollectorFirst.getName()); + System.out.println("Second name: " + nameCollectorSecond.getName()); + + } +} diff --git a/Class1/Server/src/main/java/NameCollector.java b/Class1/Server/src/main/java/NameCollector.java new file mode 100755 index 0000000..6d701ee --- /dev/null +++ b/Class1/Server/src/main/java/NameCollector.java @@ -0,0 +1,32 @@ +package main.java; + +public class NameCollector implements Runnable { + + private String name; + private Client connectedClient; + private Client outgoingClient; + private boolean isStopped = false; + + public NameCollector(Client client) { + connectedClient = client; + } + + @Override + public void run() { + name = connectedClient.readMsg(); + while (!isStopped) { + String toForward = connectedClient.readMsg(); + outgoingClient.writeMessage(toForward); + } + + } + + public void setOut(Client out) { + outgoingClient = out; + } + + public String getName() { + return name; + } + +} diff --git a/Class1/Server/src/main/java/Server.java b/Class1/Server/src/main/java/Server.java new file mode 100755 index 0000000..96c848e --- /dev/null +++ b/Class1/Server/src/main/java/Server.java @@ -0,0 +1,159 @@ +package main.java; + +import java.util.Iterator; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.logging.Logger; +import java.io.*; +import java.net.*; + +class Server { + + private ServerSocket clientListener; + private BlockingDeque clientList; + public Logger logger = Logger.getLogger(this.getClass().getName()); + public int totalConnections = 0; + private int internalSum = 0; + + public Server(int port) { + try { + clientListener = new ServerSocket(port); + clientList = new LinkedBlockingDeque<>(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void acceptClient() { + try { + logger.info("Started listening for client"); + Socket newClient = clientListener.accept(); + clientList.add(new Client(newClient)); + logger.info("Client connected from " + newClient.getInetAddress()); + totalConnections++; + } catch (IOException e) { + e.printStackTrace(); + } + } + + public String getMessageFromClient(int index) { + if (index > clientList.size() - 1 || index < 0) { + throw new RuntimeException("Client list index out of bounds"); + } + + Iterator clientIterator = clientList.iterator(); + int i = 0; + Client toRead = null; + + while (clientIterator.hasNext()) { + toRead = clientIterator.next(); + if (i == index) { + break; + } + i++; + } + + if (toRead != null) { + return toRead.readMsg(); + } else { + logger.severe("Error accessing client in queue"); + return null; + } + + } + + public void sendMessageToClient(int index, String message) { + if (index > clientList.size() - 1 || index < 0) { + throw new RuntimeException("Client list index out of bounds"); + } + + Iterator clientIterator = clientList.iterator(); + int i = 0; + Client toSend = null; + + while (clientIterator.hasNext()) { + toSend = clientIterator.next(); + if (i == index) { + break; + } + i++; + } + + if (toSend != null) { + toSend.writeMessage(message); + } else { + logger.severe("Error accessing client in queue"); + return; + } + + } + + public void echoClient(int index) { + if (index > clientList.size() - 1 || index < 0) { + throw new RuntimeException("Client list index out of bounds"); + } + + Iterator clientIterator = clientList.iterator(); + int i = 0; + Client toUse = null; + + while (clientIterator.hasNext()) { + toUse = clientIterator.next(); + if (i == index) { + break; + } + i++; + } + + if (toUse != null) { + toUse.echoFunction(); + } else { + logger.severe("Error accessing client in queue"); + return; + } + } + + public void broadcastMessage(String message) { + for (Client client : clientList) { + client.writeMessage(message); + } + } + + public Client getClient(int index) { + Iterator clientIterator = clientList.iterator(); + int i = 0; + Client ret = null; + + while (clientIterator.hasNext()) { + ret = clientIterator.next(); + if (i == index) { + break; + } + i++; + } + return ret; + } + + public void removeClient(Client client) { + client.closeClient(); + logger.info("Removing client from queue"); + clientList.remove(client); + } + + public int getClientCount() { + return clientList.size(); + } + + public void addToInternal(String num) { + try { + internalSum += Integer.parseInt(num); + } catch (NumberFormatException e) { + System.err.println("ERROR: expected integer"); + } + } + + public int getSum() { + return internalSum; + } + +} diff --git a/Class1/Server/src/main/java/Util.java b/Class1/Server/src/main/java/Util.java new file mode 100755 index 0000000..2b124b6 --- /dev/null +++ b/Class1/Server/src/main/java/Util.java @@ -0,0 +1,9 @@ +package main.java; + +public class Util { + + public static int numberFunction(int n) { + return 2*n + 1; + } + +} diff --git a/Class1/Server/src/main/resources/serverfile.txt b/Class1/Server/src/main/resources/serverfile.txt new file mode 100755 index 0000000..cc5a47d --- /dev/null +++ b/Class1/Server/src/main/resources/serverfile.txt @@ -0,0 +1,3 @@ +Server has this file, +it contains some lines +and that's it \ No newline at end of file From df1ddd395db94e7f7a1b210e86f729d0ed3881ca Mon Sep 17 00:00:00 2001 From: Jonas Gohn Date: Mon, 5 Mar 2018 19:39:24 +0100 Subject: [PATCH 2/7] fixed code and all exercises --- Class1/Client/README.md | 6 + Class1/Client/src/main/java/Client.java | 15 +- Class1/Client/src/main/java/Main.java | 122 +++++---- Class1/Server/README.md | 10 + Class1/Server/src/main/java/Client.java | 10 +- Class1/Server/src/main/java/FileIO.java | 0 Class1/Server/src/main/java/Forwarder.java | 33 +++ Class1/Server/src/main/java/Listener.java | 29 +++ Class1/Server/src/main/java/Main.java | 244 +++++++++++------- .../Server/src/main/java/NameCollector.java | 32 --- Class1/Server/src/main/java/Server.java | 26 +- Class1/Server/src/main/java/Sharer.java | 23 ++ Class1/Server/src/main/java/Util.java | 0 13 files changed, 350 insertions(+), 200 deletions(-) create mode 100644 Class1/Client/README.md create mode 100644 Class1/Server/README.md mode change 100755 => 100644 Class1/Server/src/main/java/Client.java mode change 100755 => 100644 Class1/Server/src/main/java/FileIO.java create mode 100644 Class1/Server/src/main/java/Forwarder.java create mode 100644 Class1/Server/src/main/java/Listener.java mode change 100755 => 100644 Class1/Server/src/main/java/Main.java delete mode 100755 Class1/Server/src/main/java/NameCollector.java mode change 100755 => 100644 Class1/Server/src/main/java/Server.java create mode 100644 Class1/Server/src/main/java/Sharer.java mode change 100755 => 100644 Class1/Server/src/main/java/Util.java diff --git a/Class1/Client/README.md b/Class1/Client/README.md new file mode 100644 index 0000000..d1952ee --- /dev/null +++ b/Class1/Client/README.md @@ -0,0 +1,6 @@ +CLIENT USAGE: +From src dir: +$ javac main/java/*.java +$ java main/java/Main +CL arguments: +-0,-1,-2,-3,-4,-5,-6 to execute specfic task. Only use one argument per execution. diff --git a/Class1/Client/src/main/java/Client.java b/Class1/Client/src/main/java/Client.java index 68b19cf..532e2f5 100755 --- a/Class1/Client/src/main/java/Client.java +++ b/Class1/Client/src/main/java/Client.java @@ -6,9 +6,6 @@ import java.net.*; class Client { - - private static final String DISC = "DISCONNECT"; - private Scanner reader; private PrintWriter writer; private Socket internalSocket; @@ -20,7 +17,6 @@ public Client(String hostname, int port) { internalSocket = new Socket(hostname, port); reader = new Scanner(internalSocket.getInputStream()); writer = new PrintWriter(internalSocket.getOutputStream()); - // Dont close socket because will close io streams } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { @@ -35,6 +31,7 @@ public void sendMsg(String message) { } public String readMsg() { + //Intentionally blocking request while (!reader.hasNext()) { } String message = reader.nextLine(); @@ -54,14 +51,4 @@ public void sendMsg(int message) { writer.flush(); } - public void sendDisconnect() { - writer.println(DISC); - writer.flush(); - try { - internalSocket.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } diff --git a/Class1/Client/src/main/java/Main.java b/Class1/Client/src/main/java/Main.java index e14b688..3d779b7 100755 --- a/Class1/Client/src/main/java/Main.java +++ b/Class1/Client/src/main/java/Main.java @@ -9,47 +9,92 @@ public class Main { public static final String EXIT_TOKEN = "exit"; public static void main(String[] args) { - boolean usingExtended = false; - boolean connectOnly = false; - boolean giveNumbers = false; - boolean chatMode = false; + int exNum = 0; String chatname = "Bob"; // default name int giveRandom = 5; if (args.length > 0) { - if (args[0].equals("-2e")) { - usingExtended = true; - } - - if (args[0].equals("-4")) { - connectOnly = true; - } - - if (args[0].equals("-5")) { - giveNumbers = true; - if (args.length > 1) { + switch (args[0]) { + case "-0": + exNum = 0; + break; + case "-1": + exNum = 1; + break; + case "-2": + exNum = 2; + break; + case "-3": + exNum = 3; + break; + case "-4": + exNum = 4; + break; + case "-5": + exNum = 5; + if (args.length == 2) { giveRandom = Integer.parseInt(args[1]); } - } - - if (args[0].equals("-6")) { - chatMode = true; - if (args.length > 1) { + break; + case "-6": + exNum = 6; + if (args.length == 2) { chatname = args[1]; } + break; + default: + System.out.println("Error understanding commandline argument, exiting..."); + return; } } Client client = new Client("localhost", 12345); + // Exercise 0 + if (exNum == 0) { + client.echoFunction("echo this back"); + return; + } + // Exercise 1 + if (exNum == 1) { + + client.sendMsg("4"); + String answer = client.readMsg(); + System.out.println(answer); + return; + } + // Exercise 2 + if (exNum == 2) { + + FileIO fileHandler = new FileIO("main/resources/numberfile.txt"); + ArrayList fileNumbers = (ArrayList) fileHandler.readNumbers(); + + for (int number : fileNumbers) { + client.sendMsg(number); + } + client.sendMsg(END_TOKEN); + + for (int i = 0; i < fileNumbers.size(); i++) { + String recv = client.readMsg(); + System.out.println(recv); + } + + return; + } + // Exercise 3 + if (exNum == 3) { + String filename = "serverfile.txt"; + client.sendMsg(filename); + System.out.println(client.readMsg()); + } // Exercise 4 - if (connectOnly) { + if (exNum == 4) { System.out.println("Current connection count: " + client.readMsg()); return; } // Exercise 5 - if (giveNumbers) { + if (exNum == 5) { System.out.println("Generating " + giveRandom + " random numbers and sending to server."); for (int i = 0; i < giveRandom; i++) { // some number between 0 and 20 @@ -62,7 +107,7 @@ public static void main(String[] args) { // Exercise 6 - if (chatMode) { + if (exNum == 6) { boolean isStopped = false; client.sendMsg(chatname); // One thread for reading @@ -102,37 +147,6 @@ public void run() { return; } - if (!usingExtended) { - // Exercise 0 - client.echoFunction("echo this back"); - // Exercise 1 - client.sendMsg("4"); - String answer = client.readMsg(); - System.out.println(answer); - - } - // Exercise 2 - FileIO fileHandler = new FileIO("main/resources/numberfile.txt"); - ArrayList fileNumbers = (ArrayList) fileHandler.readNumbers(); - - for (int number : fileNumbers) { - client.sendMsg(number); - } - client.sendMsg(END_TOKEN); - - for (int i = 0; i < fileNumbers.size(); i++) { - String recv = client.readMsg(); - System.out.println(recv); - } - - // Exercise 3 - String filename = "serverfile.txt"; - client.sendMsg(filename); - System.out.println(client.readMsg()); - if (usingExtended) { - return; - } - } } diff --git a/Class1/Server/README.md b/Class1/Server/README.md new file mode 100644 index 0000000..f940497 --- /dev/null +++ b/Class1/Server/README.md @@ -0,0 +1,10 @@ +SERVER USAGE: +From src dir: +$ javac main/java/*.java +$ java main/java/Main +CL arguments: +-0,-1,-2,-3,-4,-5,-6 to execute specfic task. Only use one argument per execution. +For exercises 2 and 6, server can be set for the extended versions using -2e +and -6e. -2e sets server to wait for new client after a client has finished +task. -6e enables multi client communication with up to n clients. (n can be +set in Main.java inside exercise 6 function. diff --git a/Class1/Server/src/main/java/Client.java b/Class1/Server/src/main/java/Client.java old mode 100755 new mode 100644 index 73f3cb9..48e4b71 --- a/Class1/Server/src/main/java/Client.java +++ b/Class1/Server/src/main/java/Client.java @@ -8,15 +8,16 @@ class Client { public Logger logger = Logger.getLogger(this.getClass().getName()); - public static final String DISC = "DISCONNECT"; private Scanner reader; private PrintWriter inputPrinter; + private int clientId; - public Client(Socket clientSocket) { + public Client(Socket clientSocket, int id) { try { reader = new Scanner(clientSocket.getInputStream()); inputPrinter = new PrintWriter(clientSocket.getOutputStream()); + clientId = id; } catch (IOException e) { e.printStackTrace(); } @@ -24,6 +25,7 @@ public Client(Socket clientSocket) { } public String readMsg() { + // Blocking request while (!reader.hasNext()) { } String message = reader.nextLine(); @@ -61,4 +63,8 @@ public void closeClient() { inputPrinter.close(); reader.close(); } + + public int getId() { + return clientId; + } } diff --git a/Class1/Server/src/main/java/FileIO.java b/Class1/Server/src/main/java/FileIO.java old mode 100755 new mode 100644 diff --git a/Class1/Server/src/main/java/Forwarder.java b/Class1/Server/src/main/java/Forwarder.java new file mode 100644 index 0000000..e15a28e --- /dev/null +++ b/Class1/Server/src/main/java/Forwarder.java @@ -0,0 +1,33 @@ +package main.java; + +public class Forwarder implements Runnable { + + private String name; + private Client fromClient; + private Client toClient; + private boolean isStopped = false; + + public Forwarder(Client from, Client to) { + fromClient = from; + toClient = to; + } + + @Override + public void run() { + name = fromClient.readMsg(); + while (!isStopped) { + String toForward = fromClient.readMsg(); + toClient.writeMessage(name + ":" + toForward); + } + + } + + public void setOut(Client out) { + fromClient = out; + } + + public String getName() { + return name; + } + +} diff --git a/Class1/Server/src/main/java/Listener.java b/Class1/Server/src/main/java/Listener.java new file mode 100644 index 0000000..9379835 --- /dev/null +++ b/Class1/Server/src/main/java/Listener.java @@ -0,0 +1,29 @@ +package main.java; + +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.LinkedBlockingDeque; + +import javafx.util.Pair; + +public class Listener implements Runnable { + + private Client client; + public static BlockingDeque> messageBox = new LinkedBlockingDeque<>(); + + public Listener(Client cli) { + client = cli; + } + + @Override + public void run() { + int id = client.getId(); + String name = client.readMsg(); + System.out.println("Name of client: " + name); + while (!Thread.currentThread().isInterrupted()) { + String incMsg = client.readMsg(); + Pair message = new Pair(id, incMsg); + messageBox.add(message); + } + } + +} diff --git a/Class1/Server/src/main/java/Main.java b/Class1/Server/src/main/java/Main.java old mode 100755 new mode 100644 index 3262b06..d504f80 --- a/Class1/Server/src/main/java/Main.java +++ b/Class1/Server/src/main/java/Main.java @@ -8,128 +8,180 @@ public class Main { public static final int CLIENT_COUNTER = 5; public static void main(String[] args) { - boolean extendedVersion = false; - String tmp = ""; + int exNum = 0; + boolean extended = false; + boolean manyClients = false; + if (args.length > 0) { - if (args[0].equals("-2e")) { - extendedVersion = true; + switch (args[0]) { + case "-0": + exNum = 0; + break; + case "-1": + exNum = 1; + break; + case "-2": + exNum = 2; + break; + case "-2e": + exNum = 2; + extended = true; + break; + case "-3": + exNum = 3; + break; + case "-4": + exNum = 4; + break; + case "-5": + exNum = 5; + break; + case "-6": + exNum = 6; + break; + case "-6e": + exNum = 6; + manyClients = true; + break; + default: + System.out.println("Error understanding commandline argument, exiting..."); + return; } + } + String tmp; Server server = new Server(12345); - server.acceptClient(); - Client client = server.getClient(0); - - if (!extendedVersion) { - String manyPrints = "ThisManyTimes"; - - // Exercise 0 + if (exNum == 0) { + server.acceptClient(); + Client client = server.getClient(0); client.echoFunction(); - // Exercise 1 + return; + } + if (exNum == 1) { + server.acceptClient(); + Client client = server.getClient(0); + String manyPrints = "ThisManyTimes"; tmp = client.readMsg(); int n = Integer.parseInt(tmp); client.sendNtimes(manyPrints, n); + return; } - // Exercise 2 - // For infinite clients set extendedVersion to true - - boolean happened = false; - - while (extendedVersion || !happened) { - if (extendedVersion && server.getClientCount() < 1) { - server.acceptClient(); - client = server.getClient(0); - } - - ArrayList numbersToHandle = new ArrayList<>(); + if (exNum == 2) { + server.acceptClient(); + Client client = server.getClient(0); + boolean happened = false; + while (extended || !happened) { + if (extended && server.getClientCount() == 0) { + server.acceptClient(); + client = server.getClient(0); + } + ArrayList numbersToHandle = new ArrayList<>(); + + while (!(tmp = client.readMsg()).equals(END_TOKEN)) { + try { + numbersToHandle.add(Integer.parseInt(tmp)); + } catch (NumberFormatException e) { + System.err.println("ERROR: expected integer"); + } + } - while (!(tmp = client.readMsg()).equals(END_TOKEN)) { - try { - numbersToHandle.add(Integer.parseInt(tmp)); - } catch (NumberFormatException e) { - System.err.println("ERROR: expected integer"); + for (int num : numbersToHandle) { + int tmpNumber = Util.numberFunction(num); + client.writeMessage(tmpNumber); } - } - for (int num : numbersToHandle) { - int tmpNumber = Util.numberFunction(num); - client.writeMessage(tmpNumber); + if (extended) { + server.removeClient(client); + } else { + happened = true; + } } - - if (extendedVersion) { - server.removeClient(client); + return; + } + if (exNum == 3) { + server.acceptClient(); + Client client = server.getClient(0); + String filename = client.readMsg(); + FileIO serverFile = new FileIO("main/resources/" + filename); + if (serverFile.exists()) { + String toSend = serverFile.getFileContent(); + client.writeMessage(toSend); } else { - happened = true; + client.writeMessage("ERROR: Could not find file"); } + return; } - // Exercise 3 - String filename = client.readMsg(); - FileIO serverFile = new FileIO("main/resources/" + filename); - if (serverFile.exists()) { - String toSend = serverFile.getFileContent(); - client.writeMessage(toSend); - } else { - client.writeMessage("ERROR: Could not find file"); + if (exNum == 4) { + while (server.totalConnections < CLIENT_COUNTER) { + server.acceptClient(); + // This returns newest client in queue + Client newestClient = server.getClient(server.getClientCount() - 1); + newestClient.writeMessage(server.totalConnections); + server.removeClient(newestClient); + } + return; } - - // Exercise 4 - // Removing all clients before initiating exercise 4 - if (server.getClientCount() != 1) { - System.out.println("Only expecting one client online at this time"); - + if (exNum == 5) { + while (server.getSum() < 100) { + server.acceptClient(); + Client client = server.getClient(0); + String number; + while (!(number = client.readMsg()).equals("exit")) { + server.addToInternal(number); + } + server.removeClient(client); + System.out.println("Current sum : " + server.getSum()); + } return; - } else { - server.removeClient(server.getClient(0)); } - - while (server.totalConnections < CLIENT_COUNTER) { - server.acceptClient(); - // This returns newest client in queue - Client newestClient = server.getClient(server.getClientCount() - 1); - newestClient.writeMessage(server.totalConnections); - server.removeClient(newestClient); + if (exNum == 6 && !manyClients) { + while (server.getClientCount() < 2) { + server.acceptClient(); + } + Client first = server.getClient(0); + Client second = server.getClient(1); + + Forwarder fw1 = new Forwarder(first, second); + Forwarder fw2 = new Forwarder(second, first); + + Thread t1 = new Thread(fw1); + Thread t2 = new Thread(fw2); + t1.start(); + t2.start(); + try { + System.out.println("Sleeping thread while clients talk"); + Thread.sleep(120000); + } catch (InterruptedException e) { + e.printStackTrace(); + } } - // Exercise 5 - // Assuming no active connection at this time - assert (server.getClientCount() == 0); - while (server.getSum() < 100) { - server.acceptClient(); - client = server.getClient(0); - String number; - while (!(number = client.readMsg()).equals("exit")) { - server.addToInternal(number); + if (exNum == 6 && manyClients) { + // client number + int n = 5; + System.out.println("Waiting until " + n + " clients has connected"); + while (server.getClientCount() < n) { + server.acceptClient(); } - server.removeClient(client); - System.out.println("Current sum : " + server.getSum()); - } - // Exercise 6 - while (server.getClientCount() < 2) { - server.acceptClient(); - } - Client first = server.getClient(0); - Client second = server.getClient(1); - String nameFirst; - String nameSecond; - NameCollector nameCollectorFirst = new NameCollector(first); - NameCollector nameCollectorSecond = new NameCollector(second); - - Thread t1 = new Thread(nameCollectorFirst); - Thread t2 = new Thread(nameCollectorSecond); - t1.start(); - t2.start(); - try { - t1.join(); - t2.join(); - } catch (InterruptedException e) { - e.printStackTrace(); + for (Client connClient : server.getClientList()) { + Listener list = new Listener(connClient); + Thread clientListener = new Thread(list); + clientListener.start(); + } + + Sharer sharer = new Sharer(server); + Thread broadcaster = new Thread(sharer); + broadcaster.start(); + try { + System.out.println("Started multi client broadcast"); + Thread.sleep(120000); + } catch (InterruptedException e) { + e.printStackTrace(); + } } - // Application will wait until both threads have collected name from client - System.out.println("First name: " + nameCollectorFirst.getName()); - System.out.println("Second name: " + nameCollectorSecond.getName()); - } } diff --git a/Class1/Server/src/main/java/NameCollector.java b/Class1/Server/src/main/java/NameCollector.java deleted file mode 100755 index 6d701ee..0000000 --- a/Class1/Server/src/main/java/NameCollector.java +++ /dev/null @@ -1,32 +0,0 @@ -package main.java; - -public class NameCollector implements Runnable { - - private String name; - private Client connectedClient; - private Client outgoingClient; - private boolean isStopped = false; - - public NameCollector(Client client) { - connectedClient = client; - } - - @Override - public void run() { - name = connectedClient.readMsg(); - while (!isStopped) { - String toForward = connectedClient.readMsg(); - outgoingClient.writeMessage(toForward); - } - - } - - public void setOut(Client out) { - outgoingClient = out; - } - - public String getName() { - return name; - } - -} diff --git a/Class1/Server/src/main/java/Server.java b/Class1/Server/src/main/java/Server.java old mode 100755 new mode 100644 index 96c848e..599843c --- a/Class1/Server/src/main/java/Server.java +++ b/Class1/Server/src/main/java/Server.java @@ -13,6 +13,7 @@ class Server { private BlockingDeque clientList; public Logger logger = Logger.getLogger(this.getClass().getName()); public int totalConnections = 0; + private int clientId = 0; private int internalSum = 0; public Server(int port) { @@ -28,9 +29,10 @@ public void acceptClient() { try { logger.info("Started listening for client"); Socket newClient = clientListener.accept(); - clientList.add(new Client(newClient)); + clientList.add(new Client(newClient, clientId)); logger.info("Client connected from " + newClient.getInetAddress()); totalConnections++; + clientId++; } catch (IOException e) { e.printStackTrace(); } @@ -119,6 +121,23 @@ public void broadcastMessage(String message) { } } + // Pass client as sending client so it doesnt receive same message sent + public void broadcastMessage(Client client, String message) { + for (Client cli : clientList) { + if (!cli.equals(client)) { + cli.writeMessage(message); + } + } + } + + public void broadcastMessage(int id, String message) { + for (Client cli : clientList) { + if (id != cli.getId()) { + cli.writeMessage(message); + } + } + } + public Client getClient(int index) { Iterator clientIterator = clientList.iterator(); int i = 0; @@ -155,5 +174,8 @@ public void addToInternal(String num) { public int getSum() { return internalSum; } - + + public BlockingDeque getClientList() { + return clientList; + } } diff --git a/Class1/Server/src/main/java/Sharer.java b/Class1/Server/src/main/java/Sharer.java new file mode 100644 index 0000000..56f145a --- /dev/null +++ b/Class1/Server/src/main/java/Sharer.java @@ -0,0 +1,23 @@ +package main.java; + +import javafx.util.Pair; + +public class Sharer implements Runnable { + + private Server server; + + public Sharer(Server serv) { + server = serv; + } + + @Override + public void run() { + while (!Thread.currentThread().isInterrupted()) { + if (Listener.messageBox.size() > 0) { + Pair oldestMessage = Listener.messageBox.remove(); + server.broadcastMessage(oldestMessage.getKey(), oldestMessage.getValue()); + } + } + } + +} diff --git a/Class1/Server/src/main/java/Util.java b/Class1/Server/src/main/java/Util.java old mode 100755 new mode 100644 From 1d8d59fbc2928179b7fc9c1c9c1d7e1af5ab47ec Mon Sep 17 00:00:00 2001 From: Jonas Date: Mon, 5 Mar 2018 19:44:52 +0100 Subject: [PATCH 3/7] update readme fixed formatting --- Class1/Server/README.md | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/Class1/Server/README.md b/Class1/Server/README.md index f940497..2d82d1f 100644 --- a/Class1/Server/README.md +++ b/Class1/Server/README.md @@ -1,10 +1,19 @@ -SERVER USAGE: -From src dir: -$ javac main/java/*.java -$ java main/java/Main -CL arguments: --0,-1,-2,-3,-4,-5,-6 to execute specfic task. Only use one argument per execution. -For exercises 2 and 6, server can be set for the extended versions using -2e -and -6e. -2e sets server to wait for new client after a client has finished -task. -6e enables multi client communication with up to n clients. (n can be +## SERVER USAGE: + +From src dir, to compile and execute run: + +`$ javac main/java/*.java` + +`$ java main/java/Main` + +### CL arguments: + +`-0`,`-1`,`-2`,`-3`,`-4`,`-5`,`-6` to execute specfic task. +Only use one argument per execution. + +For exercises 2 and 6, server can be set for the extended versions using `-2e` +and `-6e`. +`-2e` sets server to wait for new client after a client has finished +task 2. +`-6e` enables multi client communication with up to n clients. (n can be set in Main.java inside exercise 6 function. From 09e58abce6ef12e3219f0fdefd0f9d5cf4b9eb19 Mon Sep 17 00:00:00 2001 From: Jonas Date: Mon, 5 Mar 2018 19:48:42 +0100 Subject: [PATCH 4/7] fixed readme formatting --- Class1/Client/README.md | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/Class1/Client/README.md b/Class1/Client/README.md index d1952ee..064cae2 100644 --- a/Class1/Client/README.md +++ b/Class1/Client/README.md @@ -1,6 +1,14 @@ -CLIENT USAGE: -From src dir: -$ javac main/java/*.java -$ java main/java/Main -CL arguments: --0,-1,-2,-3,-4,-5,-6 to execute specfic task. Only use one argument per execution. +## CLIENT USAGE: + +From src dir to compile and execute do: + +`$ javac main/java/*.java` + +`$ java main/java/Main` + +### CL arguments: + +`-0`,`-1`,`-2`,`-3`,`-4`,`-5`,`-6` to execute specfic task. +Only use one argument per execution. +If executing exercise `-5`, an additional argument can be given which will be the number of random numbers given from client to server. (default=5) +If exectuing exercse `-6`, an additioanl argument can be given which will be the name of client. (default="Bob") From c7284860b6c431de9c2d63c4308e70703af4a2ee Mon Sep 17 00:00:00 2001 From: Jonas Date: Mon, 5 Mar 2018 19:49:19 +0100 Subject: [PATCH 5/7] again formatting... the readme --- Class1/Client/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Class1/Client/README.md b/Class1/Client/README.md index 064cae2..a98f4e6 100644 --- a/Class1/Client/README.md +++ b/Class1/Client/README.md @@ -10,5 +10,7 @@ From src dir to compile and execute do: `-0`,`-1`,`-2`,`-3`,`-4`,`-5`,`-6` to execute specfic task. Only use one argument per execution. + If executing exercise `-5`, an additional argument can be given which will be the number of random numbers given from client to server. (default=5) + If exectuing exercse `-6`, an additioanl argument can be given which will be the name of client. (default="Bob") From fe858232eb2f127fd5ae746c5ff3bfa978de62d2 Mon Sep 17 00:00:00 2001 From: Jonas Gohn Date: Wed, 7 Mar 2018 11:51:14 +0100 Subject: [PATCH 6/7] started server development --- Class2/application/GameCoordinator.java | 21 +++ Class2/application/Main.java | 22 +++ Class2/models/Board.java | 2 +- Class2/models/Computer.java | 2 +- Class2/models/Game.java | 210 ++++++++++++------------ Class2/models/Human.java | 135 +++++++++++---- Class2/models/Player.java | 31 ++-- 7 files changed, 267 insertions(+), 156 deletions(-) create mode 100755 Class2/application/GameCoordinator.java create mode 100755 Class2/application/Main.java diff --git a/Class2/application/GameCoordinator.java b/Class2/application/GameCoordinator.java new file mode 100755 index 0000000..8716efd --- /dev/null +++ b/Class2/application/GameCoordinator.java @@ -0,0 +1,21 @@ +package main.java.application; + +import main.java.models.Board; +import main.java.models.Human; + +public class GameCoordinator { + + private Human player1; + private Human player2; + private Board board; + + public GameCoordinator(Human player1, Human player2, Board board) { + this.player1 = player1; + this.player2 = player2; + this.board = board; + } + + + + +} diff --git a/Class2/application/Main.java b/Class2/application/Main.java new file mode 100755 index 0000000..deb0c32 --- /dev/null +++ b/Class2/application/Main.java @@ -0,0 +1,22 @@ +package main.java.application; + +import java.util.Optional; + +import main.java.models.Human; + +public class Main { + + public static void main(String[] args) { + //Game game = new Game(); + Human h = new Human(); + + Optional opt = h.parseMove("1 2"); + if(opt.isPresent()) { + System.out.println(opt.get()[0]); + System.out.println(opt.get()[1]); + } else { + System.out.println("No opt present"); + } + } + +} diff --git a/Class2/models/Board.java b/Class2/models/Board.java index 0c9b74a..a8f5cb2 100644 --- a/Class2/models/Board.java +++ b/Class2/models/Board.java @@ -1,4 +1,4 @@ -package models; +package main.java.models; public class Board { diff --git a/Class2/models/Computer.java b/Class2/models/Computer.java index 2bac030..db54196 100644 --- a/Class2/models/Computer.java +++ b/Class2/models/Computer.java @@ -1,4 +1,4 @@ -package models; +package main.java.models; public class Computer extends Player{ diff --git a/Class2/models/Game.java b/Class2/models/Game.java index 9c959fe..958ecf3 100644 --- a/Class2/models/Game.java +++ b/Class2/models/Game.java @@ -1,109 +1,109 @@ -package models; +package main.java.models; -public class Game { - private Board board; - private int turn=1, who=1; - private Player player1; - private Player player2; - public Scanner input = new Scanner(System.in); - - - public Game(){ - board = new Board(); - startPlayers(); - - while( Play() ); - } - - public void startPlayers(){ - System.out.println("Who will be player1 ?"); - if(choosePlayer() == 1) - this.player1 = new Human(1); - else - this.player1 = new Computer(1); - - System.out.println("----------------------"); - System.out.println("Who will be Player 2 ?"); - - if(choosePlayer() == 1) - this.player2 = new Human(2); - else - this.player2 = new Computer(2); - - } - - public int choosePlayer(){ - int option=0; - - do{ - System.out.println("1. Human"); - System.out.println("2. Computer\n"); - System.out.print("Option: "); - option = input.nextInt(); - - if(option != 1 && option != 2) - System.out.println("Invalid Option! Try again"); - }while(option != 1 && option != 2); - - return option; - } - - public boolean Play(){ - board.showBoard(); - if(won() == 0 ){ - System.out.println("----------------------"); - System.out.println("\nTurn "+turn); - System.out.println("It's turn of Player " + who() ); - - if(who()==1) - player1.play(board); - else - player2.play(board); - - - if(board.fullBoard()){ - System.out.println("Full Board. Draw!"); - return false; - } - who++; - turn++; - - return true; - } else{ - if(won() == -1 ) - System.out.println("Player 1 won!"); - else - System.out.println("Player 2 won!"); - - return false; - } - - } - - public int who(){ - if(who%2 == 1) - return 1; - else - return 2; - } - - public int won(){ - if(board.checkLines() == 1) - return 1; - if(board.checkColumns() == 1) - return 1; - if(board.checkDiagonals() == 1) - return 1; - - if(board.checkLines() == -1) - return -1; - if(board.checkColumns() == -1) - return -1; - if(board.checkDiagonals() == -1) - return -1; - - return 0; - } +import java.util.Scanner; +public class Game { + private Board board; + private int turn = 1, who = 1; + private Player player1; + private Player player2; + public Scanner input = new Scanner(System.in); + + public Game() { + board = new Board(); + startPlayers(); + + while (Play()) + ; + } + + public void startPlayers() { + System.out.println("Who will be player1 ?"); + if (choosePlayer() == 1) + this.player1 = new Human(); + else + this.player1 = new Computer(1); + + System.out.println("----------------------"); + System.out.println("Who will be Player 2 ?"); + + if (choosePlayer() == 1) + this.player2 = new Human(); + else + this.player2 = new Computer(2); + + } + + public int choosePlayer() { + int option = 0; + + do { + System.out.println("1. Human"); + System.out.println("2. Computer\n"); + System.out.print("Option: "); + option = input.nextInt(); + + if (option != 1 && option != 2) + System.out.println("Invalid Option! Try again"); + } while (option != 1 && option != 2); + + return option; + } + + public boolean Play() { + board.showBoard(); + if (won() == 0) { + System.out.println("----------------------"); + System.out.println("\nTurn " + turn); + System.out.println("It's turn of Player " + who()); + + if (who() == 1) + player1.play(board); + else + player2.play(board); + + if (board.fullBoard()) { + System.out.println("Full Board. Draw!"); + return false; + } + who++; + turn++; + + return true; + } else { + if (won() == -1) + System.out.println("Player 1 won!"); + else + System.out.println("Player 2 won!"); + + return false; + } + + } + + public int who() { + if (who % 2 == 1) + return 1; + else + return 2; + } + + public int won() { + if (board.checkLines() == 1) + return 1; + if (board.checkColumns() == 1) + return 1; + if (board.checkDiagonals() == 1) + return 1; + + if (board.checkLines() == -1) + return -1; + if (board.checkColumns() == -1) + return -1; + if (board.checkDiagonals() == -1) + return -1; + + return 0; + } } diff --git a/Class2/models/Human.java b/Class2/models/Human.java index 1e69d9c..40cd940 100644 --- a/Class2/models/Human.java +++ b/Class2/models/Human.java @@ -1,49 +1,114 @@ -package models; - +package main.java.models; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.Socket; +import java.util.Optional; import java.util.Scanner; +import java.util.logging.Logger; + +public class Human extends Player { + + Logger logger = Logger.getLogger(this.getClass().getName()); + + public Scanner input; + private PrintWriter out; + + public Human(int player, Socket socket) { + super(player); + this.player = player; + try { + this.out = new PrintWriter(socket.getOutputStream()); + this.input = new Scanner(socket.getInputStream()); + } catch (IOException e) { + e.printStackTrace(); + } + + System.out.println("Player 'Human' created!"); + } + + public Human() { + // TODO Auto-generated constructor stub + } + + @Override + public void play(Board board) { + Try(board); + board.setPosition(attempt, player); + } -public class Human extends Player{ - public Scanner input = new Scanner(System.in); + @Override + public void Try(Board board) { + int[] attempt; + do { + attempt = nextMove(); + if (!checkTry(attempt, board)) { + logger.info("Place already marked. Try another."); + sendMsg("ERROR: 1, target already marked"); + } + } while (!checkTry(attempt, board)); + } - public Human(int player){ - super(player); - this.player = player; - System.out.println("Player 'Human' created!"); - } + public String readMsg() { + while (!input.hasNext()) { - @Override - public void play(Board board){ - Try(board); - board.setPosition(attempt, player); - } + } + String in = input.nextLine(); + logger.info("From client: " + in); + return in; + } - @Override - public void Try(Board board){ - do{ - do{ - System.out.print("Line: "); - attempt[0] = input.nextInt(); + public void sendMsg(String msg) { + logger.info("To client: " + msg); + out.println(msg); + out.flush(); + } - if( attempt[0] > 3 ||attempt[0] < 1) - System.out.println("Invalid line. It's 1, 2 or 3"); + public int[] nextMove() { + String move = readMsg(); + Optional boardCoords = Optional.empty(); + boolean acceptedMove = false; + while (!acceptedMove) { + boardCoords = parseMove(move); - }while( attempt[0] > 3 ||attempt[0] < 1); + if (!boardCoords.isPresent()) { + logger.severe("Got empty coords!"); + sendMsg("ERROR: 2, bad coordinates"); + logger.info("Waiting for next coordinate msg"); + move = readMsg(); + } else { + acceptedMove = true; + } + } - do{ - System.out.print("Column: "); - attempt[1] = input.nextInt(); + return boardCoords.get(); + } - if(attempt[1] > 3 ||attempt[1] < 1) - System.out.println("Invalid column. É 1, 2 or 3"); + public Optional parseMove(String strMove) { + // accept move in format (x,y) || x,y || x y + int[] move = new int[2]; + if (strMove.contains(",")) { + if (strMove.contains("(")) { + strMove = strMove.replaceAll("\\(", ""); + strMove = strMove.replaceAll("\\)", ""); + } + String[] tokens = strMove.split(","); - }while(attempt[1] > 3 ||attempt[1] < 1); + if (tokens.length != 2) { + logger.severe("Coordinates not following format! Try again..."); + return Optional.empty(); + } else { + move[0] = Integer.parseInt(tokens[0]); + move[1] = Integer.parseInt(tokens[1]); + return Optional.of(move); + } + } else { + String[] tokens = strMove.split(" "); + move[0] = Integer.parseInt(tokens[0]); + move[1] = Integer.parseInt(tokens[1]); + return Optional.of(move); + } - attempt[0]--; - attempt[1]--; + } - if(!checkTry(attempt, board)) - System.out.println("Placed already marked. Try other."); - }while( !checkTry(attempt, board) ); - } } diff --git a/Class2/models/Player.java b/Class2/models/Player.java index b4f8496..ac8e366 100644 --- a/Class2/models/Player.java +++ b/Class2/models/Player.java @@ -1,25 +1,28 @@ -package models; +package main.java.models; public abstract class Player { - protected int[] attempt = new int[2]; - protected int player; + protected int[] attempt = new int[2]; + protected int player; + public Player(int player) { + this.player = player; + } - public Player(int player){ - this.player = player; - } + public Player() { - public abstract void play(Board board); + } - public abstract void Try(Board board); + public abstract void play(Board board); - public boolean checkTry(int[] attempt, Board board){ - if(board.getPosition(attempt) == 0) - return true; - else - return false; + public abstract void Try(Board board); - } + public boolean checkTry(int[] attempt, Board board) { + if (board.getPosition(attempt) == 0) + return true; + else + return false; + + } } From b41ae5b2713e9cf75bd91f4acee808ca8f83ef90 Mon Sep 17 00:00:00 2001 From: Jonas Gohn Date: Wed, 7 Mar 2018 11:57:24 +0100 Subject: [PATCH 7/7] adding server.java --- Class2/application/Server.java | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100755 Class2/application/Server.java diff --git a/Class2/application/Server.java b/Class2/application/Server.java new file mode 100755 index 0000000..e69ed24 --- /dev/null +++ b/Class2/application/Server.java @@ -0,0 +1,39 @@ +package main.java.application; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.concurrent.BlockingDeque; +import java.util.concurrent.LinkedBlockingDeque; + +import main.java.models.Human; + +public class Server { + + private ServerSocket serverSock; + private BlockingDeque players; + + public Server(int port) { + try { + serverSock = new ServerSocket(port); + players = new LinkedBlockingDeque<>(); + } catch (IOException e) { + e.printStackTrace(); + } + } + + public void waitForPlayers() { + int playerCount = 2; + int curPlayerIndex = 1; + while (players.size() < playerCount) { + try { + Socket sock = serverSock.accept(); + players.add(new Human(curPlayerIndex++, sock)); + } catch (IOException e) { + e.printStackTrace(); + } + } + + } + +}