|
| 1 | +package org.javawebstack.httpserver.adapter.undertow; |
| 2 | + |
| 3 | +import io.undertow.Undertow; |
| 4 | +import io.undertow.server.handlers.BlockingHandler; |
| 5 | +import io.undertow.websockets.core.WebSocketVersion; |
| 6 | +import org.javawebstack.httpserver.adapter.IHTTPSocketHandler; |
| 7 | +import org.javawebstack.httpserver.adapter.IHTTPSocketServer; |
| 8 | +import org.javawebstack.httpserver.util.websocket.WebSocketUtil; |
| 9 | +import org.xnio.Options; |
| 10 | + |
| 11 | +import java.io.IOException; |
| 12 | +import java.io.InputStream; |
| 13 | +import java.io.OutputStream; |
| 14 | +import java.util.concurrent.ExecutorService; |
| 15 | +import java.util.concurrent.Executors; |
| 16 | + |
| 17 | +public class UndertowHTTPSocketServer implements IHTTPSocketServer { |
| 18 | + |
| 19 | + private int port = 80; |
| 20 | + private Undertow server; |
| 21 | + private IHTTPSocketHandler handler; |
| 22 | + private ExecutorService executorService; |
| 23 | + |
| 24 | + public void setPort(int port) { |
| 25 | + this.port = port; |
| 26 | + } |
| 27 | + |
| 28 | + public int getPort() { |
| 29 | + return port; |
| 30 | + } |
| 31 | + |
| 32 | + public void start() throws IOException { |
| 33 | + executorService = Executors.newCachedThreadPool(); |
| 34 | + server = Undertow.builder() |
| 35 | + .addHttpListener(port, "0.0.0.0") |
| 36 | + .setServerOption(Options.KEEP_ALIVE, true) |
| 37 | + .setHandler(new BlockingHandler(httpServerExchange -> { |
| 38 | + if(httpServerExchange.getRequestHeaders().contains("sec-websocket-key")) { |
| 39 | + httpServerExchange.upgradeChannel((streamConnection, httpServerExchange1) -> { |
| 40 | + InputStream inputStream = new StreamSourceInputStream(streamConnection.getSourceChannel()); |
| 41 | + OutputStream outputStream = new StreamSinkOutputStream(streamConnection.getSinkChannel()); |
| 42 | + handler.handle(new UndertowHTTPSocket(httpServerExchange1, inputStream, outputStream)); |
| 43 | + }); |
| 44 | + httpServerExchange.putAttachment(WebSocketVersion.ATTACHMENT_KEY, WebSocketVersion.V13); |
| 45 | + if(!WebSocketUtil.accept(new UndertowHTTPSocket(httpServerExchange, null, null), null)) |
| 46 | + return; |
| 47 | + httpServerExchange.endExchange(); |
| 48 | + } else { |
| 49 | + handler.handle(new UndertowHTTPSocket(httpServerExchange, null, null)); |
| 50 | + } |
| 51 | + })) |
| 52 | + .build(); |
| 53 | + server.start(); |
| 54 | + } |
| 55 | + |
| 56 | + public void stop() { |
| 57 | + executorService.shutdown(); |
| 58 | + server.stop(); |
| 59 | + } |
| 60 | + |
| 61 | + public void join() { |
| 62 | + try { |
| 63 | + server.getWorker().awaitTermination(); |
| 64 | + } catch (InterruptedException e) {} |
| 65 | + } |
| 66 | + |
| 67 | + public void setHandler(IHTTPSocketHandler handler) { |
| 68 | + this.handler = handler; |
| 69 | + } |
| 70 | + |
| 71 | + public boolean isWebSocketSupported() { |
| 72 | + return true; |
| 73 | + } |
| 74 | + |
| 75 | +} |
0 commit comments