|
| 1 | +package io.reactivesocket.netty; |
| 2 | + |
| 3 | +import io.netty.buffer.ByteBuf; |
| 4 | +import io.netty.channel.ChannelHandlerContext; |
| 5 | +import io.netty.channel.ChannelPipeline; |
| 6 | +import io.netty.channel.SimpleChannelInboundHandler; |
| 7 | +import io.netty.handler.codec.ByteToMessageDecoder; |
| 8 | +import io.netty.handler.codec.http.FullHttpRequest; |
| 9 | +import io.netty.handler.codec.http.HttpObjectAggregator; |
| 10 | +import io.netty.handler.codec.http.HttpServerCodec; |
| 11 | +import io.reactivesocket.RequestHandler; |
| 12 | +import io.reactivesocket.netty.tcp.server.ReactiveSocketServerHandler; |
| 13 | + |
| 14 | +import java.util.List; |
| 15 | + |
| 16 | +public class EchoServerHandler extends ByteToMessageDecoder { |
| 17 | + private static SimpleChannelInboundHandler<FullHttpRequest> httpHandler = new HttpServerHandler(); |
| 18 | + |
| 19 | + private static ReactiveSocketServerHandler reactiveSocketHandler = ReactiveSocketServerHandler.create((setupPayload, rs) -> |
| 20 | + new RequestHandler.Builder().withRequestResponse(payload -> s -> { |
| 21 | + s.onNext(payload); |
| 22 | + s.onComplete(); |
| 23 | + }).build()); |
| 24 | + |
| 25 | + @Override |
| 26 | + protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { |
| 27 | + // Will use the first five bytes to detect a protocol. |
| 28 | + if (in.readableBytes() < 5) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + final int magic1 = in.getUnsignedByte(in.readerIndex()); |
| 33 | + final int magic2 = in.getUnsignedByte(in.readerIndex() + 1); |
| 34 | + if (isHttp(magic1, magic2)) { |
| 35 | + switchToHttp(ctx); |
| 36 | + } else { |
| 37 | + switchToReactiveSocket(ctx); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private static boolean isHttp(int magic1, int magic2) { |
| 42 | + return |
| 43 | + magic1 == 'G' && magic2 == 'E' || // GET |
| 44 | + magic1 == 'P' && magic2 == 'O' || // POST |
| 45 | + magic1 == 'P' && magic2 == 'U' || // PUT |
| 46 | + magic1 == 'H' && magic2 == 'E' || // HEAD |
| 47 | + magic1 == 'O' && magic2 == 'P' || // OPTIONS |
| 48 | + magic1 == 'P' && magic2 == 'A' || // PATCH |
| 49 | + magic1 == 'D' && magic2 == 'E' || // DELETE |
| 50 | + magic1 == 'T' && magic2 == 'R' || // TRACE |
| 51 | + magic1 == 'C' && magic2 == 'O'; // CONNECT |
| 52 | + } |
| 53 | + |
| 54 | + private void switchToHttp(ChannelHandlerContext ctx) { |
| 55 | + ChannelPipeline p = ctx.pipeline(); |
| 56 | + p.addLast(new HttpServerCodec()); |
| 57 | + p.addLast(new HttpObjectAggregator(64 * 1024)); |
| 58 | + p.addLast(httpHandler); |
| 59 | + p.remove(this); |
| 60 | + } |
| 61 | + |
| 62 | + private void switchToReactiveSocket(ChannelHandlerContext ctx) { |
| 63 | + ChannelPipeline p = ctx.pipeline(); |
| 64 | + p.addLast(reactiveSocketHandler); |
| 65 | + p.remove(this); |
| 66 | + } |
| 67 | +} |
0 commit comments