use of io.netty.handler.codec.http.HttpObject in project jocean-http by isdom.
the class HttpServerDemo method main.
public static void main(final String[] args) throws Exception {
SelfSignedCertificate ssc = new SelfSignedCertificate();
final // SslContext.newServerContext(ssc.certificate(), ssc.privateKey());
SslContext sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
// create for LocalChannel
@SuppressWarnings("resource") final HttpServerBuilder server = new DefaultHttpServerBuilder(new AbstractBootstrapCreator(new DefaultEventLoopGroup(1), new DefaultEventLoopGroup()) {
@Override
protected void initializeBootstrap(final ServerBootstrap bootstrap) {
bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
bootstrap.channel(LocalServerChannel.class);
}
}, Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(sslCtx));
@SuppressWarnings("unused") final Subscription subscription = server.defineServer(new LocalAddress("test")).subscribe(new Action1<HttpTrade>() {
@Override
public void call(final HttpTrade trade) {
trade.outbound(trade.inbound().compose(RxNettys.message2fullreq(trade)).map(DisposableWrapperUtil.<FullHttpRequest>unwrap()).map(new Func1<FullHttpRequest, HttpObject>() {
@Override
public HttpObject call(final FullHttpRequest fullreq) {
try {
final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(Nettys.dumpByteBufAsBytes(fullreq.content())));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}));
}
});
@SuppressWarnings("resource") final DefaultHttpClient client = new DefaultHttpClient(new TestChannelCreator(), Feature.ENABLE_LOGGING, new Feature.ENABLE_SSL(SslContextBuilder.forClient().build()));
while (true) {
final ByteBuf content = Unpooled.buffer(0);
content.writeBytes("test content".getBytes("UTF-8"));
final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/", content);
HttpUtil.setContentLength(request, content.readableBytes());
/* // TODO using initiator
final Iterator<HttpObject> itr =
client.defineInteraction(
new LocalAddress("test"),
Observable.just(request))
.map(RxNettys.<HttpObject>retainer())
.toBlocking().toIterable().iterator();
final byte[] bytes = RxNettys.httpObjectsAsBytes(itr);
LOG.info("recv Response: {}", new String(bytes, "UTF-8"));
*/
Thread.sleep(1000);
}
}
use of io.netty.handler.codec.http.HttpObject in project jocean-http by isdom.
the class TestHttpUtil method buildBytesResponse.
public static Observable<HttpObject> buildBytesResponse(final String contentType, final byte[] content) {
final FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, OK, Unpooled.wrappedBuffer(content));
response.headers().set(HttpHeaderNames.CONTENT_TYPE, contentType);
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
return Observable.<HttpObject>just(response);
}
use of io.netty.handler.codec.http.HttpObject in project jocean-http by isdom.
the class RxNettys method response404NOTFOUND.
public static Observable<HttpObject> response404NOTFOUND(final HttpVersion version) {
final HttpResponse response = new DefaultFullHttpResponse(version, HttpResponseStatus.NOT_FOUND);
response.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
return Observable.<HttpObject>just(response);
}
use of io.netty.handler.codec.http.HttpObject in project netty by netty.
the class WebSocketServerProtocolHandshakeHandler method channelRead.
@Override
public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
final HttpObject httpObject = (HttpObject) msg;
if (httpObject instanceof HttpRequest) {
final HttpRequest req = (HttpRequest) httpObject;
isWebSocketPath = isWebSocketPath(req);
if (!isWebSocketPath) {
ctx.fireChannelRead(msg);
return;
}
try {
if (!GET.equals(req.method())) {
sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN, ctx.alloc().buffer(0)));
return;
}
final WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(ctx.pipeline(), req, serverConfig.websocketPath()), serverConfig.subprotocols(), serverConfig.decoderConfig());
final WebSocketServerHandshaker handshaker = wsFactory.newHandshaker(req);
final ChannelPromise localHandshakePromise = handshakePromise;
if (handshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
// Ensure we set the handshaker and replace this handler before we
// trigger the actual handshake. Otherwise we may receive websocket bytes in this handler
// before we had a chance to replace it.
//
// See https://github.com/netty/netty/issues/9471.
WebSocketServerProtocolHandler.setHandshaker(ctx.channel(), handshaker);
ctx.pipeline().remove(this);
final ChannelFuture handshakeFuture = handshaker.handshake(ctx.channel(), req);
handshakeFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
localHandshakePromise.tryFailure(future.cause());
ctx.fireExceptionCaught(future.cause());
} else {
localHandshakePromise.trySuccess();
// Kept for compatibility
ctx.fireUserEventTriggered(WebSocketServerProtocolHandler.ServerHandshakeStateEvent.HANDSHAKE_COMPLETE);
ctx.fireUserEventTriggered(new WebSocketServerProtocolHandler.HandshakeComplete(req.uri(), req.headers(), handshaker.selectedSubprotocol()));
}
}
});
applyHandshakeTimeout();
}
} finally {
ReferenceCountUtil.release(req);
}
} else if (!isWebSocketPath) {
ctx.fireChannelRead(msg);
} else {
ReferenceCountUtil.release(msg);
}
}
use of io.netty.handler.codec.http.HttpObject in project vert.x by eclipse.
the class Http1xServerResponse method end.
private void end(Buffer chunk, PromiseInternal<Void> listener) {
synchronized (conn) {
if (written) {
throw new IllegalStateException(RESPONSE_WRITTEN);
}
ByteBuf data = chunk.getByteBuf();
bytesWritten += data.readableBytes();
HttpObject msg;
if (!headWritten) {
// if the head was not written yet we can write out everything in one go
// which is cheaper.
prepareHeaders(bytesWritten);
msg = new AssembledFullHttpResponse(head, version, status, headers, data, trailingHeaders);
} else {
msg = new AssembledLastHttpContent(data, trailingHeaders);
}
conn.writeToChannel(msg, listener);
written = true;
conn.responseComplete();
if (bodyEndHandler != null) {
bodyEndHandler.handle(null);
}
if (!closed && endHandler != null) {
endHandler.handle(null);
}
if (!keepAlive) {
closeConnAfterWrite();
closed = true;
}
}
}
Aggregations