...
| Code Block | ||
|---|---|---|
| ||
class SocketReader implements Runnable {
private static ThreadLocal<Socket> connectionHolder = new ThreadLocal<Socket>() {
Socket socket = null;
@Override public Socket initialValue() {
try {
socket = new Socket("defaultHost", "defaultPort");25); // 25 is the default port to connect to
} catch (UnknownHostException e) {
// Forward to handler
} catch (IOException e) {
// Forward to handler
}
return socket;
}
@Override public void set(Socket sock) {
if(sock == null) { // Shuts down socket when null value is passed
try {
socket.close();
} catch (IOException e) {
// Forward to handler
}
} else {
socket = sock; // Assigns Socket with caller specified hostname and port
}
}
};
public static Socket getSocketConnection() {
return connectionHolder.get();
}
public static void shutdownSocket() { // Allows client to close socket anytime
connectionHolder.set(null);
}
public void run() {
Socket socket = getSocketConnection();
// Do some useful work
}
}
|
...