Skip to content

Instantly share code, notes, and snippets.

@JamieAP
Created February 25, 2016 15:58
Show Gist options
  • Save JamieAP/98cf55eaf0e4e7c8d3db to your computer and use it in GitHub Desktop.
Save JamieAP/98cf55eaf0e4e7c8d3db to your computer and use it in GitHub Desktop.
import com.google.common.base.Throwables;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
private static final ExecutorService executor = Executors.newFixedThreadPool(5);
public static void main(String[] args) throws IOException {
new Main().listen();
}
private void listen() throws IOException {
ServerSocket servSoc = new ServerSocket(1200);
while (true) {
acceptConnection(servSoc);
System.out.println("Opened socket");
}
}
private void handleSocket(Socket soc) {
try {
InputStreamReader isr = new InputStreamReader(soc.getInputStream());
while (true) {
if (soc.isClosed()) {
isr.close();
System.out.println("Socket closed");
return;
}
recvData(soc, isr);
System.out.println();
}
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
private void acceptConnection(ServerSocket servSoc) throws IOException {
Socket socket = servSoc.accept();
executor.submit(() -> handleSocket(socket));
}
private void recvData(Socket soc, InputStreamReader isr) throws IOException {
waitForData(soc, isr);
while (true) {
int read = isr.read();
if (read == -1) {
soc.close();
return;
}
System.out.print(Character.toChars(read));
}
}
private void waitForData(Socket soc, InputStreamReader isr) throws IOException {
while (!isr.ready() && !soc.isClosed()) {}
return;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment