SocketListener

import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Socket listener for unit test to listen for messages.
 *
 * @author dev
 *
 */
public class SocketListener {
String host;
int port;

ServerSocket s;

ExecutorService executor = Executors.newSingleThreadExecutor();

public SocketListener(String host, int port) {
this.host = host;
this.port = port;
}

public SocketListener init() {
try {
s = new ServerSocket(port, 10, Inet4Address.getByName(host));
Worker worker = new Worker();
executor.submit(worker);
} catch (IOException e) {
throw new RuntimeException("Failed to listen", e);
}
return this;
}

public void close() {
if (s != null) {
try {
s.close();
} catch (IOException e) {
// ignore
}
}
}

public class Worker implements Runnable {

@Override
public void run() {
Socket k = null;
try {
while (true) {
k = s.accept();
InputStream is = k.getInputStream();

int b = -1;
while ((b = is.read()) != -1) {
System.out.print(String.format("%02x", (byte) b));
System.out.print(".");
// TODO ugh what's the structure
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

Comments

Popular posts from this blog

Sites, Newsletters, and Blogs

Oracle JDBC ReadTimeout QueryTimeout

Locks held on Oracle for hours after sessions abnormally terminated by node failure