Minimal WebSocket server example in Java

The following code is a very minimal example of a WebSocket server implemented in java. All it does is to echo back what it receives in uppercase.
This example is based on the use of Java-WebSocket.

public class WSServer extends WebSocketServer {

  private final DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

  public WSServer(int port) {
    super(new InetSocketAddress(port));
    System.out.println("Websocket server running... Listning on port " + port);
  }

  @Override
  public void onOpen(WebSocket ws, ClientHandshake ch) {
    Date date = new Date();
    System.out.println("");
    System.out.println(dateFormat.format(date) + " : " + ws.getRemoteSocketAddress() + " connected!");
  }

  @Override
  public void onClose(WebSocket ws, int i, String string, boolean bln) {
    Date date = new Date();
    System.out.println(dateFormat.format(date) + " : " + ws.getRemoteSocketAddress() + " disconnected!");
  }

  @Override
  public void onMessage(WebSocket ws, String string) {
    Date date = new Date();
    System.out.println(dateFormat.format(date) + " : " + ws.getRemoteSocketAddress() + " got: " + string);
    ws.send(string.toUpperCase());
  }

  @Override
  public void onError(WebSocket ws, Exception excptn) {
    Date date = new Date();
    System.out.println(dateFormat.format(date) + " : " + ws.getRemoteSocketAddress() + " Error!");
  }

  public static void main(String[] args) {
    int port = 8888;
    if (args.length != 1) {
      System.out.println("No port provided. Defaulting to port " + port);
    } else {
      try {
        port = Integer.parseInt(args[0]);
      } catch (NumberFormatException ex) {
        System.out.println("Error, port is not a valid number. Defaulting to port " + port);
      }
    }
    new WSServer(port).start();
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *