Skip to content

Instantly share code, notes, and snippets.

@twood02
Created November 15, 2018 17:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twood02/8d1e4f2c97f4daf21b2d737384de0756 to your computer and use it in GitHub Desktop.
Save twood02/8d1e4f2c97f4daf21b2d737384de0756 to your computer and use it in GitHub Desktop.
KnockKnock Server
package knockknock;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by timwood@seas.gwu.edu on 11/16/16.
*/
public class KnockServer {
public KnockServer() {
ServerSocket serverSocket = null;
boolean listening = true;
System.out.println("Waiting for connections...");
try {
serverSocket = new ServerSocket(6666);
} catch (IOException e) {
System.err.println("Could not listen on port: 6666.");
System.exit(-1);
}
while (listening) {
try {
// wait for a connection
Socket sock = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
System.out.println("Got connection from " + sock.getInetAddress());
String msg;
msg = in.readLine();
System.out.println("Client:" + msg);
out.println("Who is there?");
System.out.println("Server: Who is there");
msg = in.readLine();
System.out.println("Client:" + msg);
out.println(msg + " who?");
System.out.println(msg + " who?");
msg = in.readLine(); // the punchline
System.out.println("Client:" + msg);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new KnockServer();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment