commit e69313d6e7545f5e4c3c7f707d2077db551a00db
parent 963372746807ffba26698c1c23698842ae845861
Author: David Engel <dengel@ucalgary.ca>
Date: Fri, 28 Apr 2017 21:30:54 -0600
server: actually added the Java files...
Diffstat:
3 files changed, 118 insertions(+), 0 deletions(-)
diff --git a/shlist/Hooker.java b/shlist/Hooker.java
@@ -0,0 +1,31 @@
+package shlist;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.util.concurrent.ExecutorService;
+
+// Shutdown Hook
+// kills resources if we get ctrl-c
+// should close DB and sockets and whatnot
+// output something to the log file?
+public class Hooker extends Thread {
+ private ServerSocket ss;
+ private ExecutorService exec;
+
+ public void run() {
+ System.out.println("");
+ try {
+ ss.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ exec.shutdown();
+ while (!exec.isTerminated()) { }
+ System.out.println("Clean Exit");
+ }
+
+ public Hooker(ServerSocket ss, ExecutorService exec) {
+ this.ss = ss;
+ this.exec = exec;
+ }
+}
diff --git a/shlist/Server.java b/shlist/Server.java
@@ -0,0 +1,41 @@
+package shlist;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+public class Server {
+
+ public final static int THREAD_COUNT = 4;
+ public final static int PORT = 5437;
+
+ public static void main(String[] args) {
+
+ ExecutorService exec = Executors.newFixedThreadPool(THREAD_COUNT);
+
+ ServerSocket sSock = null;
+ Socket sock = null;
+
+ try {
+ sSock = new ServerSocket(PORT);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+
+ // Add the runtime hook, for ctrl+c
+ Runtime r = Runtime.getRuntime();
+ r.addShutdownHook(new Hooker(sSock, exec));
+
+ while (true) {
+ try {
+ sock = sSock.accept();
+ } catch (IOException e) {
+ System.out.println("IO Error: " + e);
+ break;
+ }
+ exec.execute(new Worker(sock));
+ }
+ }
+}
diff --git a/shlist/Worker.java b/shlist/Worker.java
@@ -0,0 +1,46 @@
+package shlist;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.Socket;
+
+public class Worker implements Runnable {
+ private Socket sock;
+
+ public Worker(Socket s) {
+ this.sock = s;
+ }
+
+ public void run() {
+ InputStream inp = null;
+ BufferedReader brinp = null;
+ try {
+ inp = sock.getInputStream();
+ brinp = new BufferedReader(new InputStreamReader(inp));
+ } catch (IOException e) {
+ e.printStackTrace();
+ return;
+ }
+ System.out.println("Started new thread");
+ String line;
+ while (true) {
+ try {
+ line = brinp.readLine();
+ if (line != null) {
+ System.out.println(line);
+ } else {
+ sock.close();
+ brinp.close();
+ System.out.println("Closing Socket");
+ break;
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ return;
+ }
+ }
+ System.out.println("Exiting Thread");
+ }
+}