1 package fi.iki.elonen; 2 3 4 public class NanoWebSocketServer extends NanoHTTPD implements IWebSocketFactory { 5 public static final String MISSING_FACTORY_MESSAGE = "You must either override this method or supply a WebSocketFactory in the constructor"; 6 7 private final WebSocketResponseHandler responseHandler; 8 NanoWebSocketServer(int port)9 public NanoWebSocketServer(int port) { 10 super(port); 11 responseHandler = new WebSocketResponseHandler(this); 12 } 13 NanoWebSocketServer(String hostname, int port)14 public NanoWebSocketServer(String hostname, int port) { 15 super(hostname, port); 16 responseHandler = new WebSocketResponseHandler(this); 17 } 18 NanoWebSocketServer(int port, IWebSocketFactory webSocketFactory)19 public NanoWebSocketServer(int port, IWebSocketFactory webSocketFactory) { 20 super(port); 21 responseHandler = new WebSocketResponseHandler(webSocketFactory); 22 } 23 NanoWebSocketServer(String hostname, int port, IWebSocketFactory webSocketFactory)24 public NanoWebSocketServer(String hostname, int port, IWebSocketFactory webSocketFactory) { 25 super(hostname, port); 26 responseHandler = new WebSocketResponseHandler(webSocketFactory); 27 } 28 29 @Override serve(IHTTPSession session)30 public Response serve(IHTTPSession session) { 31 Response candidate = responseHandler.serve(session); 32 return candidate == null ? super.serve(session) : candidate; 33 } 34 openWebSocket(IHTTPSession handshake)35 public WebSocket openWebSocket(IHTTPSession handshake) { 36 throw new Error(MISSING_FACTORY_MESSAGE); 37 } 38 } 39 40