package protocol_sockets.example; import java.io.*; import protocol_sockets.*; /** *

* This server waits for a {@link ExampleClient} to connect. When it gets a * connection, it sends a "hello" message and than waits to the client to send * a username and password. *

* * @author Stephen G. Ware */ public class ExampleServer extends Thread { /** The port to listen on */ private final int port; /** *

* Main constructor *

* * @param port the port to listen on */ public ExampleServer(int port){ this.port = port; } /** *

* When a client connects, send a "hello" message and then wait via * {@link ProcotolServer#sendAndWaitForResponse(String, String) * ProcotolServer#sendAndWaitForResponse(String, String)}. After getting * the information, print it to the console, tell the client to * disconnect, and shut down. *

*/ public void run() { try{ // Start listening for connections ProtocolServerSocket server = new ProtocolServerSocket(port); System.out.println("SERVER IS NOW RUNNING"); // Get a new connection ProtocolSocket socket = (ProtocolSocket) server.accept(); // Send a "hello" message and specify what response to wait for String[] credentials = socket.sendAndWaitForResponse( "", "(.*)(.*)"); // Print the information System.out.println("USER \"" + credentials[0] + "\" CONNECTED WITH PASSWORD \"" + credentials[1] + "\""); // Tell the client to disconnect System.out.println("SERVER IS SHUTTING DOWN"); socket.send(""); Thread.sleep(100); // Shut down server.close(); System.out.println("SERVER IS SHUT DOWN"); } catch(IOException ex){ ex.printStackTrace(); } catch (InterruptedException ex){ ex.printStackTrace(); } } }