Continuation from here
Suppose you have the following bit of a single-threaded socket server in Java 7 (and assuming that I didn't miss parens or what-not ... At work, I don't have a dev environment on an Internet-facing box):
This would require a "driver" something like:
Is "run" fully refactored/extracted? Does it do "one thing"? One could argue that you could factor out the initialization bits into an init() method which would require the ServerSocket to be a class member/field. Or, you could push the ServerSocket handling down a level, and make it look like:
Is this going too far? Does it really make sense? Or am I just begging for trouble?
Is "handleClientConnection" fully refactored/extracted?
In fact, I need TWO slightly different single-threaded socket servers, but the only difference in them are the ports and what is done with the incoming text-based data, so, a refactoring leads to:
requiring a driver that looks like:
This complicates things such as Exception handling... where do I handle the exceptions? Or just let them trickle up? Certainly we don't want an exception to stop the main loop which is accepting connections as that would cause the entire program to exit and possibly lose data.
Also, now I've added a complication in that there is no way to close the writer inside LoggingClientHandler if/when I *DO* go to a multi-threaded model (not to mention a "global" handler handling multiple connections with the internal state...)
And, in truth, I HAVE taken it further and factored out the public void process(String line) bit into an InputLineProcessor interface with a LoggingLineProcessor which works as above. :sigh:
So I guess I'm asking ... Would you do anything remarkably different?
Suppose you have the following bit of a single-threaded socket server in Java 7 (and assuming that I didn't miss parens or what-not ... At work, I don't have a dev environment on an Internet-facing box):
Code:
/**
* File: SingleThreadSocketServer.java
*
* Listens on a port and processes the text data coming from client connections.
* Single-threaded; only allows one client connection at a time
*/
public class SingleThreadSocketServer implements Runnable {
private static final Logger LOG = Logger.getLogger(SingleThreadSocketServer.class.getName());
private volatile running = false;
private final int port;
public SingleThreadSocketServer(int port) {
this.port = port;
}
// main processing, Thread Runnable
public void run() {
running = true;
try (ServerSocket socket = new ServerSocket(port)) {
while(running) {
try (Socket client = socket.accept()) {
handleClientConnection(client);
}
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "", e);
}
}
// read input from the client inputstream and process it line by line
// assumes: string/text-based input
private void handleClientConnection(Socket client) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
String line;
while((line = reader.readLine()) != null) {
process(line);
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "", e);
}
}
// process the line
private void process(String line) {
// do stuff with the line
}
}
This would require a "driver" something like:
Code:
public class Main {
public static void main(String[] args) {
Runnable server = new SingleThreadSocketServer(8080);
server.run();
}
}
Is "run" fully refactored/extracted? Does it do "one thing"? One could argue that you could factor out the initialization bits into an init() method which would require the ServerSocket to be a class member/field. Or, you could push the ServerSocket handling down a level, and make it look like:
Code:
public void run() {
running = true;
try (ServerSocket socket = new ServerSocket(port)) {
handleServerSocket(socket);
} catch (IOException e) {
LOG.log(Level.SEVERE, "", e);
}
}
public void handleServerSocket(ServerSocket socket) {
while(running) {
try (Socket client = socket.accept()) {
handleClientConnection(client);
} catch (IOException e) {
LOG.log(Level.SEVERE, "", e);
}
}
}
Is this going too far? Does it really make sense? Or am I just begging for trouble?
Is "handleClientConnection" fully refactored/extracted?
In fact, I need TWO slightly different single-threaded socket servers, but the only difference in them are the ports and what is done with the incoming text-based data, so, a refactoring leads to:
Code:
/**
* File: ClientConnectionHandler.java
*
* Interface which defines how to handle a client connection via Socket
*/
public interface ClientConnectionHandler {
public void handleClientConnection(Socket client);
}
/**
* File: SingleThreadedSocketServer.java
*
* Single threaded socket server
* User must provide a ClientConnectionHandler to handle connections
*/
public class SingleThreadSocketServer implements Runnable {
private static final Logger LOG = Logger.getLogger(SingleThreadSocketServer.class.getName());
private volatile running = false;
private final int port;
private final ClientConnectionHandler handler;
public SingleThreadSocketServer(int port, ClientConnectionHandler handler) {
this.port = port;
this.handler = handler;
}
// main processing, Thread Runnable
public void run() {
running = true;
try (ServerSocket socket = new ServerSocket(port)) {
while(running) {
try (Socket client = socket.accept()) {
handler.handleClientConnection(client);
}
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "", e);
}
}
}
/**
* LoggingClientHandler.java
*
* ClientConnectionHandler which simply writes all incoming data out to a log file.
*/
public class LoggingClientHandler implements ClientConnectionHandler {
private final Writer writer;
public LoggingClientHandler(String logFilePath) {
this.writer = new PrintWriter(logFilePath);
}
// read input from the client inputstream and process it line by line
// assumes: string/text-based input
@Override
public void handleClientConnection(Socket client) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()))) {
String line;
while((line = reader.readLine()) != null) {
process(line);
}
} catch (IOException e) {
LOG.log(Level.SEVERE, "", e);
}
}
// process the line
private void process(String line) {
writer.println(new Date() + ": " + line);
writer.flush();
}
}
requiring a driver that looks like:
Code:
public class LoggingServer {
public static void main(String[] args) {
// assumes args[0] contains the path to the logging directory
ClientConnectionHandler handler = new LoggingClientHandler(args[0]);
// assumes args[1] contains the port to listen on
int port = Integer.parseInt(args[1]);
SingleThreadSocketServer server = new SingleThreadSocketServer(port, handler);
server.run();
}
}
This complicates things such as Exception handling... where do I handle the exceptions? Or just let them trickle up? Certainly we don't want an exception to stop the main loop which is accepting connections as that would cause the entire program to exit and possibly lose data.
Also, now I've added a complication in that there is no way to close the writer inside LoggingClientHandler if/when I *DO* go to a multi-threaded model (not to mention a "global" handler handling multiple connections with the internal state...)
And, in truth, I HAVE taken it further and factored out the public void process(String line) bit into an InputLineProcessor interface with a LoggingLineProcessor which works as above. :sigh:
So I guess I'm asking ... Would you do anything remarkably different?