List of usage examples for io.netty.util CharsetUtil UTF_8
Charset UTF_8
To view the source code for io.netty.util CharsetUtil UTF_8.
Click Source Link
From source file:com.ahanda.techops.noty.clientTest.ClientHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { assert msg instanceof FullHttpResponse; l.info(" Got a message from server !!! {}", msg); ++state;/*from w w w . j a v a 2 s . c o m*/ if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; System.out.println("STATUS: " + response.getStatus()); System.out.println("VERSION: " + response.getProtocolVersion()); System.out.println(); if (!response.headers().isEmpty()) { for (String name : response.headers().names()) { for (String value : response.headers().getAll(name)) { System.out.println("HEADER: " + name + " = " + value); } } System.out.println(); } if (HttpHeaders.isTransferEncodingChunked(response)) { System.out.println("CHUNKED CONTENT {"); } else { System.out.println("CONTENT {"); } } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; System.out.print(content.content().toString(CharsetUtil.UTF_8)); System.out.flush(); if (content instanceof LastHttpContent) { System.out.println("} END OF CONTENT"); } } switch (state) { case 1: FullHttpResponse resp = (FullHttpResponse) msg; for (String cookiestr : resp.headers().getAll(HttpHeaders.Names.SET_COOKIE)) { Set<Cookie> tmp = CookieDecoder.decode(cookiestr); sessCookies = tmp; } //login( ctx.channel(), credential ); pubEvent(ctx.channel(), event, (FullHttpResponse) msg); break; case 2: getEvents(ctx.channel(), (FullHttpResponse) msg); break; case 3: logout(ctx.channel()); break; default: ctx.close(); break; } }
From source file:com.alibaba.dubbo.qos.server.handler.QosProcessHandler.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 1) { return;/* www . j a va 2s.c o m*/ } // read one byte to guess protocol final int magic = in.getByte(in.readerIndex()); ChannelPipeline p = ctx.pipeline(); p.addLast(new LocalHostPermitHandler(acceptForeignIp)); if (isHttp(magic)) { // no welcome output for http protocol if (welcomeFuture != null && welcomeFuture.isCancellable()) { welcomeFuture.cancel(false); } p.addLast(new HttpServerCodec()); p.addLast(new HttpObjectAggregator(1048576)); p.addLast(new HttpProcessHandler()); p.remove(this); } else { p.addLast(new LineBasedFrameDecoder(2048)); p.addLast(new StringDecoder(CharsetUtil.UTF_8)); p.addLast(new StringEncoder(CharsetUtil.UTF_8)); p.addLast(new IdleStateHandler(0, 0, 5 * 60)); p.addLast(new TelnetProcessHandler()); p.remove(this); } }
From source file:com.athena.dolly.websocket.client.test.WebSocketClientHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { Channel ch = ctx.channel();//from w ww . j av a 2 s. com if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; System.out.println("WebSocket Client received message: " + textFrame.text()); } else if (frame instanceof PongWebSocketFrame) { System.out.println("WebSocket Client received pong"); } else if (frame instanceof CloseWebSocketFrame) { System.out.println("WebSocket Client received closing"); ch.close(); } }
From source file:com.athena.dolly.websocket.server.test.WebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);// w ww. j av a 2 s . c o m buf.release(); setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.athena.dolly.websocket.server.test.WebSocketSslServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // Generate an error page if response getStatus code is not OK (200). if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);/*from w w w . ja v a 2s .c o m*/ buf.release(); setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().write(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.bala.learning.learning.netty.HttpServerHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest request = this.request = (HttpRequest) msg; if (HttpHeaders.is100ContinueExpected(request)) { send100Continue(ctx);// ww w .j a va2s . c o m } buf.setLength(0); buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); buf.append("===================================\r\n"); buf.append("VERSION: ").append(request.getProtocolVersion()).append("\r\n"); buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n"); buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n"); HttpHeaders headers = request.headers(); if (!headers.isEmpty()) { for (Map.Entry<String, String> h : headers) { String key = h.getKey(); String value = h.getValue(); buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n"); } buf.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map<String, List<String>> params = queryStringDecoder.parameters(); if (!params.isEmpty()) { for (Entry<String, List<String>> p : params.entrySet()) { String key = p.getKey(); List<String> vals = p.getValue(); for (String val : vals) { buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n"); } } buf.append("\r\n"); } appendDecoderResult(buf, request); } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { buf.append("CONTENT: "); buf.append(content.toString(CharsetUtil.UTF_8)); buf.append("\r\n"); appendDecoderResult(buf, request); } if (msg instanceof LastHttpContent) { buf.append("END OF CONTENT\r\n"); LastHttpContent trailer = (LastHttpContent) msg; if (!trailer.trailingHeaders().isEmpty()) { buf.append("\r\n"); for (String name : trailer.trailingHeaders().names()) { for (String value : trailer.trailingHeaders().getAll(name)) { buf.append("TRAILING HEADER: "); buf.append(name).append(" = ").append(value).append("\r\n"); } } buf.append("\r\n"); } if (!writeResponse(trailer, ctx)) { // If keep-alive is off, close the connection once the content is fully written. ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } } } }
From source file:com.bala.learning.learning.netty.HttpServerHandler.java
License:Apache License
private boolean writeResponse(HttpObject currentObj, ChannelHandlerContext ctx) { // Decide whether to close the connection or not. boolean keepAlive = HttpHeaders.isKeepAlive(request); // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.getDecoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); if (keepAlive) { // Add 'Content-Length' header only for a keep-alive connection. response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // Add keep alive header as per: // - http://www.w3.org/Protocols/HTTP/1.1/draft-ietf-http-v11-spec-01.html#Connection response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); }/*from w w w .j a v a 2 s. c o m*/ // Encode the cookie. String cookieString = request.headers().get(COOKIE); if (cookieString != null) { Set<Cookie> cookies = CookieDecoder.decode(cookieString); if (!cookies.isEmpty()) { // Reset the cookies if necessary. for (Cookie cookie : cookies) { response.headers().add(SET_COOKIE, ServerCookieEncoder.encode(cookie)); } } } else { // Browser sent no cookie. Add some. response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key1", "value1")); response.headers().add(SET_COOKIE, ServerCookieEncoder.encode("key2", "value2")); } // Write the response. ctx.write(response); return keepAlive; }
From source file:com.baoxue.netty.file.FileServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from ww w . j av a 2 s. c om*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).childHandler(new ChannelInitializer<SocketChannel>() { /* * (non-Javadoc) * * @see * io.netty.channel.ChannelInitializer#initChannel(io * .netty.channel.Channel) */ public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8), new LineBasedFrameDecoder(1024), new StringDecoder(CharsetUtil.UTF_8), new FileServerHandler()); } }); ChannelFuture f = b.bind(port).sync(); System.out.println("Start file server at port : " + port); f.channel().closeFuture().sync(); } finally { // ? bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.barchart.http.server.PooledServerResponse.java
License:BSD License
void init(final ChannelHandlerContext context_, final HttpRequestChannelHandler channelHandler_, final RequestHandler handler_, final PooledServerRequest request_, final RequestLogger logger_) { // Reset default request values if this is a recycled handler if (finished) { headers().clear();/* w w w. j a va 2 s . c o m*/ content().clear(); setStatus(HttpResponseStatus.OK); } // Reference count increment so underlying ByteBuf is not collected // between requests retain(); context = context_; channelHandler = channelHandler_; handler = handler_; request = request_; logger = logger_; charSet = CharsetUtil.UTF_8; finished = false; suspended = false; started = false; out = new ByteBufOutputStream(content()); writer = new OutputStreamWriter(out, charSet); requestTime = System.currentTimeMillis(); }
From source file:com.barchart.netty.server.http.pipeline.PooledHttpServerResponse.java
License:BSD License
void init(final ChannelHandlerContext context_, final KeepaliveHelper keepaliveHelper_, final PooledHttpServerRequest request_) { // Prevent underlying ByteBuf from being collected between requests retain();/*from w ww. j a v a 2 s .co m*/ // Reset default request values if this is a recycled handler if (finished) { headers().clear(); content().clear(); setStatus(HttpResponseStatus.OK); } context = context_; request = request_; keepaliveHelper = keepaliveHelper_; charSet = CharsetUtil.UTF_8; chunkSize = 0; finished = false; started = false; out = new CloseableByteBufOutputStream(content()); writer = new OutputStreamWriter(out, charSet); }