commit 1c569e1fa432adc0131e6f6c1934ef856fbb8879
parent eec509229cea2745297f313e42d3457a47b0a3d9
Author: Cody Lewis <luxdotsugi@gmail.com>
Date: Wed, 15 Aug 2018 10:31:14 +1000
Got the initial server working
Diffstat:
2 files changed, 71 insertions(+), 2 deletions(-)
diff --git a/ChatClient.java b/ChatClient.java
@@ -5,6 +5,31 @@
* @author Cody Lewis
* @since 2018-08-10
*/
+import java.net.Socket;
+import java.net.UnknownHostException;
+import java.io.IOException;
public class ChatClient {
-
+ private Socket socket;
+ public static void main(String args[]) {
+ ChatClient cc = new ChatClient();
+ cc.run(args);
+ System.exit(0);
+ }
+ public void run(String args[]) {
+ String hostName = args[0];
+ int port = Integer.parseInt(args[1]);
+ System.out.println(String.format("Connecting to %s:%d", hostName, port));
+ connectToServer(hostName, port);
+ System.out.println("Connected to server");
+ }
+ private boolean connectToServer(String hostName, int port) {
+ try {
+ socket = new Socket(hostName, port);
+ return true;
+ } catch(UnknownHostException uhe) {
+ return false;
+ } catch(IOException ioe) {
+ return false;
+ }
+ }
}
\ No newline at end of file
diff --git a/ChatServer.java b/ChatServer.java
@@ -1,3 +1,9 @@
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.Scanner;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.io.IOException;
/**
* ChatServer.java - Seng3400A1
* A socket based half duplex chat server
@@ -6,5 +12,43 @@
* @since 2018-08-10
*/
public class ChatServer {
-
+ private ServerSocket serverSocket;
+ private Socket cliSocket;
+ private static final int BACKLOG = 1; // Max length for queue of messages
+ public static void main(String args[]) {
+ ChatServer cs = new ChatServer();
+ cs.run(args);
+ System.exit(0);
+ }
+ /**
+ * The main flow of the program
+ * @param args The arguments sent in with the program
+ */
+ public void run(String args[]) {
+ InetAddress hostInetAddress;
+ try {
+ hostInetAddress = InetAddress.getLocalHost();
+ int port = Integer.parseInt(args[1]);
+ System.out.println(String.format("Starting server on %s:%d", hostInetAddress.getHostAddress(), port));
+ startSocket(hostInetAddress, port);
+ } catch(UnknownHostException uhe) {
+ System.err.println("That host does not exist");
+ }
+ }
+ /**
+ * Start a server socket
+ * @param hostAddress The ip address for the host server
+ * @param port The port to run the server on
+ * @return True on successful start else false
+ */
+ private boolean startSocket(InetAddress hostAddress, int port) {
+ try {
+ serverSocket = new ServerSocket(port, BACKLOG, hostAddress);
+ cliSocket = serverSocket.accept();
+ return true;
+ } catch(IOException ioe) {
+ System.err.println("No client connected");
+ return false;
+ }
+ }
}
\ No newline at end of file