Skip to content

Instantly share code, notes, and snippets.

@noahlz
Created December 1, 2011 05:36
Show Gist options
  • Select an option

  • Save noahlz/1414005 to your computer and use it in GitHub Desktop.

Select an option

Save noahlz/1414005 to your computer and use it in GitHub Desktop.
A simple server with which you can interact over a raw socket.
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