Skip to content

Commit

Permalink
T4
Browse files Browse the repository at this point in the history
  • Loading branch information
unclebob committed Aug 6, 2014
1 parent 989a30c commit b5bfec0
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
32 changes: 24 additions & 8 deletions src/cleancoderscom/socketserver/SocketServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,22 @@
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class SocketServer {
private final int port;
private final SocketService service;
private boolean running;
private ServerSocket serverSocket;
private ExecutorService executor;

public SocketServer(int port, SocketService service) {
public SocketServer(int port, SocketService service) throws Exception {
this.port = port;
this.service = service;
serverSocket = new ServerSocket(port);
executor = Executors.newFixedThreadPool(4);
}

public int getPort() {
Expand All @@ -23,20 +30,29 @@ public SocketService getService() {
}

public void start() throws Exception {
ServerSocket ss = new ServerSocket(port);
run(ss);
running = true;
}
Runnable connectionHandler = new Runnable() {
public void run() {
try {
Socket serviceSocket = serverSocket.accept();
service.serve(serviceSocket);
} catch (IOException e) {
if(running)
e.printStackTrace();
}
}
};
executor.execute(connectionHandler);

private void run(ServerSocket ss) throws IOException {
Socket serviceSocket = ss.accept();
running = true;
}

public boolean isRunning() {
return running;
}

public void stop() {
public void stop() throws Exception {
executor.awaitTermination(500, TimeUnit.MILLISECONDS);
serverSocket.close();
running = false;
}
}
12 changes: 12 additions & 0 deletions test/cleancoderscom/tests/socketserver/SocketServerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

import cleancoderscom.socketserver.SocketServer;
import cleancoderscom.socketserver.SocketService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.net.Socket;

import static junit.framework.TestCase.assertFalse;
Expand All @@ -24,6 +26,11 @@ public void setUp() throws Exception {
server = new SocketServer(port, service);
}

@After
public void tearDown() throws Exception {
server.stop();
}

@Test
public void instantiate() throws Exception {
assertEquals(port, server.getPort());
Expand Down Expand Up @@ -53,6 +60,11 @@ public static class FakeSocketService implements SocketService {

public void serve(Socket s) {
connections++;
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

0 comments on commit b5bfec0

Please sign in to comment.