List of usage examples for io.netty.buffer Unpooled copiedBuffer
private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset)
From source file:books.netty.protocol.udp.ChineseProverbClient.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {//from ww w . java 2 s . c o 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.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 w ww. ja va2 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 w w . java 2 s.c o m 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 w w w .ja v a 2 s . co m // 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
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;/*from w w w. j ava2 s. com*/ if (currentAction.equals("Add")) response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().isSuccess() ? CREATED : BAD_REQUEST); else if (currentAction.equals("Latest")) { response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().isSuccess() ? OK : BAD_REQUEST, Unpooled.copiedBuffer(buf.toString(), CharsetUtil.UTF_8)); response.headers().set(CONTENT_TYPE, "application/json; charset=utf-8"); } else response = new DefaultFullHttpResponse(HTTP_1_1, currentObj.decoderResult().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); } // Write the response. ctx.write(response); return keepAlive; }
From source file:c5db.codec.WebSocketServerIndexPage.java
License:Apache License
public static ByteBuf getContent(String webSocketLocation) { return Unpooled.copiedBuffer("<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>" + NEWLINE + "<script type=\"text/javascript\">" + NEWLINE + "var socket;" + NEWLINE + "if (!window.WebSocket) {" + NEWLINE + " window.WebSocket = window.MozWebSocket;" + NEWLINE + '}' + NEWLINE + "if (window.WebSocket) {" + NEWLINE + " socket = new WebSocket(\"" + webSocketLocation + "\");" + NEWLINE + " socket.onmessage = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = ta.value + '\\n' + event.data" + NEWLINE + " };" + NEWLINE + " socket.onopen = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = \"Web Socket opened!\";" + NEWLINE + " };" + NEWLINE + " socket.onclose = function(event) {" + NEWLINE + " var ta = document.getElementById('responseText');" + NEWLINE + " ta.value = ta.value + \"Web Socket closed\"; " + NEWLINE + " };" + NEWLINE + "} else {" + NEWLINE + " alert(\"Your browser does not support Web Socket.\");" + NEWLINE + '}' + NEWLINE + NEWLINE + "function send(message) {" + NEWLINE + " if (!window.WebSocket) { return; }" + NEWLINE + " if (socket.readyState == WebSocket.OPEN) {" + NEWLINE + " socket.send(message);" + NEWLINE + " } else {" + NEWLINE + " alert(\"The socket is not open.\");" + NEWLINE + " }" + NEWLINE + '}' + NEWLINE + "</script>" + NEWLINE + "<form onsubmit=\"return false;\">" + NEWLINE + "<input type=\"text\" name=\"message\" value=\"Hello, World!\"/>" + "<input type=\"button\" value=\"Send Web Socket Data\"" + NEWLINE + " onclick=\"send(this.form.message.value)\" />" + NEWLINE + "<h3>Output</h3>" + NEWLINE + "<textarea id=\"responseText\" style=\"width:500px;height:300px;\"></textarea>" + NEWLINE + "</form>" + NEWLINE + "</body>" + NEWLINE + "</html>" + NEWLINE, CharsetUtil.US_ASCII); }
From source file:ca.lambtoncollege.netty.webSocket.ServerHandlerWebSocket.java
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 www. jav a2 s.c o m*/ buf.release(); HttpHeaders.setContentLength(res, res.content().readableBytes()); } // Send the response and close the connection if necessary. ChannelFuture f = ctx.channel().writeAndFlush(res); if (!HttpHeaders.isKeepAlive(req) || res.getStatus().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:cf.component.http.JsonTextResponseRequestHandler.java
License:Open Source License
@Override public HttpResponse handleRequest(HttpRequest request, Matcher uriMatcher, ByteBuf body) throws RequestException { final String responseBody = handle(request, uriMatcher, body); final ByteBuf buffer = Unpooled.copiedBuffer(responseBody, CharsetUtil.UTF_8); final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buffer);/*w w w .ja v a 2s. c o m*/ final HttpHeaders headers = response.headers(); headers.add(HttpHeaders.Names.CONTENT_TYPE, "application/json; charset=UTF-8"); headers.add(HttpHeaders.Names.CONTENT_LENGTH, buffer.readableBytes()); return response; }
From source file:ch07.handlers.HttpSnoopServerHandler.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.decoderResult().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 www. java 2 s .co 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:chapter10.WebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // /*w w w. j av a 2 s . c o m*/ if (res.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().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.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }