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:books.netty.protocol.file.FileServer.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*from w w w. jav a2 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) { 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:books.netty.protocol.http.fileServer.HttpFileServerHandler.java
License:Apache License
private static void sendListing(ChannelHandlerContext ctx, File dir) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); StringBuilder buf = new StringBuilder(); String dirPath = dir.getPath(); buf.append("<!DOCTYPE html>\r\n"); buf.append("<html><head><title>"); buf.append(dirPath);//from ww w. j a v a2 s . co m buf.append(" "); buf.append("</title></head><body>\r\n"); buf.append("<h3>"); buf.append(dirPath).append(" "); buf.append("</h3>\r\n"); buf.append("<ul>"); buf.append("<li><a href=\"../\">..</a></li>\r\n"); for (File f : dir.listFiles()) { if (f.isHidden() || !f.canRead()) { continue; } String name = f.getName(); if (!ALLOWED_FILE_NAME.matcher(name).matches()) { continue; } buf.append("<li><a href=\""); buf.append(name); buf.append("\">"); buf.append(name); buf.append("</a></li>\r\n"); } buf.append("</ul></body></html>\r\n"); ByteBuf buffer = Unpooled.copiedBuffer(buf, CharsetUtil.UTF_8); response.content().writeBytes(buffer); buffer.release(); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:books.netty.protocol.http.fileServer.HttpFileServerHandler.java
License:Apache License
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:books.netty.protocol.http.xml.server.HttpXmlServerHandler.java
License:Apache License
private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, status, Unpooled.copiedBuffer(": " + status.toString() + "\r\n", CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "text/plain; charset=UTF-8"); ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); }
From source file:books.netty.protocol.udp.ChineseProverbClient.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/* w w w . j a v a 2s. co m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true) .handler(new ChineseProverbClientHandler()); Channel ch = b.bind(0).sync().channel(); // ?UDP? ch.writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("?", CharsetUtil.UTF_8), new InetSocketAddress("255.255.255.255", port))).sync(); if (!ch.closeFuture().await(15000)) { System.out.println("!"); } } finally { group.shutdownGracefully(); } }
From source file:books.netty.protocol.udp.ChineseProverbClientHandler.java
License:Apache License
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket msg) { String response = msg.content().toString(CharsetUtil.UTF_8); if (response.startsWith(": ")) { System.out.println(response); ctx.close();/* w ww. ja v a 2 s . c om*/ } }
From source file:books.netty.protocol.udp.ChineseProverbServerHandler.java
License:Apache License
public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) { String req = packet.content().toString(CharsetUtil.UTF_8); System.out.println(req);//from ww w.j a v a2 s .c om if ("?".equals(req)) { ctx.writeAndFlush(new DatagramPacket( Unpooled.copiedBuffer(": " + nextQuote(), CharsetUtil.UTF_8), packet.sender())); } }
From source file:books.netty.protocol.websocket.server.WebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // /*from w ww . jav a 2 s. c om*/ if (res.getStatus().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf); buf.release(); setContentLength(res, res.content().readableBytes()); } // ?Keep-Alive ChannelFuture f = ctx.channel().writeAndFlush(res); if (!isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:brave.netty.http.TestHttpHandler.java
License:Apache License
private boolean writeResponse(HttpResponseStatus responseStatus, String content, ChannelHandlerContext ctx) { if (StringUtil.isNullOrEmpty(content)) { content = Unpooled.EMPTY_BUFFER.toString(); }//from www . j a va 2s. com // Decide whether to close the connection or not. boolean keepAlive = isKeepAlive(httpRequest); if (responseStatus == null) { responseStatus = httpRequest.getDecoderResult().isSuccess() ? OK : BAD_REQUEST; } // Build the response object. FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, responseStatus, Unpooled.copiedBuffer(content, 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, Values.KEEP_ALIVE); } // Write the response. ctx.write(response); return keepAlive; }
From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.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);// www .j a va 2s. com } String uri = request.uri(); HttpMethod method = request.method(); Root root = Root.getInstance(); buf.setLength(0); contentBuf.setLength(0); if (method == HttpMethod.POST) { if (uri.equals("/chitchat")) { currentAction = "Add"; } } if (method == HttpMethod.GET) { if (uri.startsWith(LATEST)) { latestFromWho = decode(uri.substring(LATEST_SIZE)); currentAction = "Latest"; Message m = root.getLatest(latestFromWho); if (m != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(m.toJSON()); } } if (uri.startsWith(THREADCALL)) { currentAction = "Thread"; String threadId = uri.substring(THREADCALL_SIZE); MessageThread mt = root.getMessageThread(threadId); if (mt != null) { //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715} buf.append(mt.toJSON()); } } if (uri.startsWith(SEARCH)) { String stringToSearch = decode(uri.substring(SEARCH_SIZE)); currentAction = "search"; List<Message> lm = root.search(stringToSearch); //[{"author":"Loki", "text":"I have an army !", "thread":3, //"createdAt":1404736639710}, {"author":"Iron Man", "text":"We have a Hulk !", // "thread":3, "createdAt":1404736639715}] buf.append("["); if (!lm.isEmpty()) { Iterator<Message> it = lm.iterator(); Message m = it.next(); buf.append(m.toJSON()); while (it.hasNext()) { m = it.next(); buf.append(", "); buf.append(m.toJSON()); } } buf.append("]"); } } } if (msg instanceof HttpContent) { Root root = Root.getInstance(); HttpContent httpContent = (HttpContent) msg; ByteBuf content = httpContent.content(); if (content.isReadable()) { contentBuf.append(content.toString(CharsetUtil.UTF_8)); } if (msg instanceof LastHttpContent) { // buf.append("END OF CONTENT\r\n"); if (currentAction.equals("Add")) { addMessageFromContent(contentBuf.toString(), root); currentAction = "None"; } LastHttpContent trailer = (LastHttpContent) msg; 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); } } } }