-
-
Save twood02/8d1e4f2c97f4daf21b2d737384de0756 to your computer and use it in GitHub Desktop.
KnockKnock Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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