| 53 | import fi.iki.elonen.NanoWSD.WebSocketFrame.OpCode; |
| 54 | |
| 55 | public abstract class NanoWSD extends NanoHTTPD { |
| 56 | |
| 57 | public static enum State { |
| 58 | UNCONNECTED, |
| 59 | CONNECTING, |
| 60 | OPEN, |
| 61 | CLOSING, |
| 62 | CLOSED |
| 63 | } |
| 64 | |
| 65 | public static abstract class WebSocket { |
| 66 | |
| 67 | private final InputStream in; |
| 68 | |
| 69 | private OutputStream out; |
| 70 | |
| 71 | private WebSocketFrame.OpCode continuousOpCode = null; |
| 72 | |
| 73 | private final List<WebSocketFrame> continuousFrames = new LinkedList<WebSocketFrame>(); |
| 74 | |
| 75 | private State state = State.UNCONNECTED; |
| 76 | |
| 77 | private final NanoHTTPD.IHTTPSession handshakeRequest; |
| 78 | |
| 79 | private final NanoHTTPD.Response handshakeResponse = new NanoHTTPD.Response(NanoHTTPD.Response.Status.SWITCH_PROTOCOL, null, (InputStream) null, 0) { |
| 80 | |
| 81 | @Override |
| 82 | protected void send(OutputStream out) { |
| 83 | WebSocket.this.out = out; |
| 84 | WebSocket.this.state = State.CONNECTING; |
| 85 | super.send(out); |
| 86 | WebSocket.this.state = State.OPEN; |
| 87 | WebSocket.this.onOpen(); |
| 88 | readWebsocket(); |
| 89 | } |
| 90 | }; |
| 91 | |
| 92 | public WebSocket(NanoHTTPD.IHTTPSession handshakeRequest) { |
| 93 | this.handshakeRequest = handshakeRequest; |
| 94 | this.in = handshakeRequest.getInputStream(); |
| 95 | |
| 96 | this.handshakeResponse.addHeader(NanoWSD.HEADER_UPGRADE, NanoWSD.HEADER_UPGRADE_VALUE); |
| 97 | this.handshakeResponse.addHeader(NanoWSD.HEADER_CONNECTION, NanoWSD.HEADER_CONNECTION_VALUE); |
| 98 | } |
| 99 | |
| 100 | public boolean isOpen() { |
| 101 | return state == State.OPEN; |
| 102 | } |
| 103 | |
| 104 | public State getState() { return this.state; } |
| 105 | |
| 106 | protected abstract void onOpen(); |
| 107 | |
| 108 | protected abstract void onClose(CloseCode code, String reason, boolean initiatedByRemote); |
| 109 | |
| 110 | protected abstract void onMessage(WebSocketFrame message); |
| 111 | |
| 112 | protected abstract void onPong(WebSocketFrame pong); |