Created
December 1, 2011 05:36
-
-
Save noahlz/1414005 to your computer and use it in GitHub Desktop.
A simple server with which you can interact over a raw socket.
This file contains hidden or 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
| import java.io.*; | |
| import java.net.ServerSocket; | |
| import java.net.Socket; | |
| import java.net.SocketTimeoutException; | |
| /** | |
| * A simple server with which you can interact over a raw socket. | |
| */ | |
| public class SimpleServer { | |
| public static void main(String[] args) throws IOException { | |
| final int TIMEOUT = 3000; | |
| final int PORT = 9292; | |
| ServerSocket server = new ServerSocket(PORT); | |
| server.setSoTimeout(TIMEOUT); | |
| Socket connection = null; | |
| boolean stillRunning = true; | |
| try { | |
| while(stillRunning) { | |
| try { | |
| System.out.println("Waiting for a connection on port " + PORT + "..."); | |
| connection = server.accept(); | |
| System.out.println("Received connection!"); | |
| stillRunning = handleUserSession(connection); | |
| connection.close(); | |
| } catch (SocketTimeoutException e) { | |
| if(Thread.currentThread().isInterrupted()) { | |
| System.err.println("Shutdown requested...exiting"); | |
| stillRunning = false; | |
| } | |
| } | |
| } | |
| } finally { | |
| if(connection != null) connection.close(); | |
| } | |
| } | |
| private static boolean handleUserSession(Socket connection) throws IOException { | |
| BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); | |
| BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream())); | |
| boolean userLoggedOn = true; | |
| boolean serverShouldBeRunning = true; | |
| while(userLoggedOn) { | |
| writer.write("Ready for command:"); | |
| writer.newLine(); | |
| writer.flush(); | |
| String command = reader.readLine(); | |
| if("shutdown".equals(command)) { | |
| System.out.println("Received shutdown command!"); | |
| writer.write("** SHUTTING DOWN SERVER IMMEDIATELY"); | |
| writer.newLine(); | |
| userLoggedOn = false; | |
| serverShouldBeRunning = false; | |
| } else if ("goodbye".equals(command)) { | |
| System.out.println("User logoff"); | |
| writer.write("Goodbye!"); | |
| writer.newLine(); | |
| userLoggedOn = false; | |
| } else { | |
| System.out.println("Received command: " + command); | |
| writer.write("Received command: '" + command + "'"); | |
| writer.newLine(); | |
| } | |
| writer.flush(); | |
| } | |
| return serverShouldBeRunning; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment