Skip to content

Instantly share code, notes, and snippets.

@austintraver
Created April 23, 2020 01:41
Show Gist options
  • Save austintraver/deeb9a7b90dac2510f511cf2e32b4257 to your computer and use it in GitHub Desktop.
Save austintraver/deeb9a7b90dac2510f511cf2e32b4257 to your computer and use it in GitHub Desktop.
public class Server extends Thread {
private Socket clientSocket;
private BufferedReader fromClient;
private DataOutputStream toClient;
Server(Socket socket) {
this.clientSocket = socket;
}
public static void main (String args[]) throws Exception {
ServerSocket serverSocket = new ServerSocket (
8888, 10, InetAddress.getByName("example.com"));
System.out.println("Server started running on [" +
serverSocket.getInetAddress() + ":" + serverSocket.getLocalPort() + "] @ " + getNow());
while(true) {
Socket connected = serverSocket.accept();
Server pts = new Server(connected);
pts.start();
}
}
public void run() {
String line = null;
String contentLength = null;
String clientInfo = null;
try {
clientInfo = clientSocket.getInetAddress() + ":" + clientSocket.getPort();
System.out.println("---------------------");
System.out.println("Client [" + clientInfo + "] is connected @ " + getNow());
fromClient = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
toClient = new DataOutputStream(clientSocket.getOutputStream());
line = fromClient.readLine();
String header = line;
System.out.println(header);
StringTokenizer tokenizer = new StringTokenizer(header);
String httpMethod = tokenizer.nextToken();
if (httpMethod.equals("POST")) {
while ((line = fromClient.readLine()) != null) {
System.out.println("line: " + line);
}
} else {
System.out.println("Received something-else-request.");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
System.out.println(clientInfo + " logout @ " + getNow());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment