List of usage examples for io.netty.buffer Unpooled copiedBuffer
private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset)
From source file:com.jjneko.jjnet.networking.http.server.WebSocketHttpServerHandler.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.status().code() != 200) { ByteBuf buf = Unpooled.copiedBuffer(res.status().toString(), CharsetUtil.UTF_8); res.content().writeBytes(buf);/* ww w . j a v a 2 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.status().code() != 200) { f.addListener(ChannelFutureListener.CLOSE); } }
From source file:com.jjneko.jjnet.networking.http.server.WebSocketHttpServerTestPage.java
License:Apache License
public static ByteBuf getContent(String webSocketLocation) { return Unpooled.copiedBuffer( "<html><body><p style=\"font-size:22px;\">This peer is accessible!</p></body></html>" /* "<html><head><title>Web Socket Test</title></head>" + NEWLINE + "<body>" + NEWLINE +/*from w w w. jav a2 s .c o m*/ "<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.UTF_8); }
From source file:com.jjzhk.Chapter10.xml.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:com.jjzhk.Chapter11.websocket.WebSocketServerHandler.java
License:Apache License
private static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpRequest req, FullHttpResponse res) { // ?????//from w w w .j ava2 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:com.jjzhk.Chapter12.udp.ChineseProverbClient.java
License:Apache License
public void run(int port) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w . jav a 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(); // ???????DP 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:com.jjzhk.Chapter12.udp.ChineseProverbServerHandler.java
License:Apache License
@Override public void messageReceived(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception { String req = packet.content().toString(CharsetUtil.UTF_8); System.out.println(req);//www . j a va2s . co m if ("???".equals(req)) { ctx.writeAndFlush(new DatagramPacket( Unpooled.copiedBuffer("???: " + nextQuote(), CharsetUtil.UTF_8), packet.sender())); } }
From source file:com.leadtone.riders.server.RidersWebSocketServerHandler.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) { res.content().writeBytes(Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8)); setContentLength(res, res.content().readableBytes()); }// w w w. jav a2 s . c om // 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.linecorp.armeria.server.http.Http1RequestDecoder.java
License:Apache License
private void fail(ChannelHandlerContext ctx, HttpResponseStatus status) { discarding = true;/*from www . j a va 2 s .c om*/ req = null; final ChannelFuture future; if (receivedRequests <= sentResponses) { // Just close the connection if sending an error response will make the number of the sent // responses exceed the number of the received requests, which doesn't make sense. future = ctx.writeAndFlush(Unpooled.EMPTY_BUFFER); } else { final ByteBuf content = Unpooled.copiedBuffer(status.toString(), StandardCharsets.UTF_8); final FullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, content); final HttpHeaders headers = res.headers(); headers.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.CLOSE); headers.set(HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8); headers.setInt(HttpHeaderNames.CONTENT_LENGTH, content.readableBytes()); future = ctx.writeAndFlush(res); } future.addListener(ChannelFutureListener.CLOSE); }
From source file:com.linecorp.armeria.server.thrift.ThriftServiceCodec.java
License:Apache License
private static DefaultFullHttpResponse errorResponse(HttpResponseStatus status) { final DefaultFullHttpResponse res = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, Unpooled.copiedBuffer(status.toString(), StandardCharsets.UTF_8)); res.headers().set(HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8.toString()); return res;//from w w w . j ava 2 s .c o m }
From source file:com.linkedin.r2.transport.http.client.TestRAPClientCodec.java
License:Apache License
@Test(dataProvider = "responseData") public void testResponseDecoder(int status, String entity, HttpHeaders headers, String[] cookies) { final EmbeddedChannel ch = new EmbeddedChannel(new RAPClientCodec()); ByteBuf content = Unpooled.copiedBuffer(entity, CHARSET); FullHttpResponse nettyResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(status), content); nettyResponse.headers().set(headers); for (String cookie : cookies) { nettyResponse.headers().add(HttpHeaderNames.SET_COOKIE, cookie); }/*www . j a va 2 s . c o m*/ ch.writeInbound(nettyResponse); RestResponse response = (RestResponse) ch.readInbound(); Assert.assertEquals(response.getStatus(), status); Assert.assertEquals(response.getEntity().asString(CHARSET), entity); assertList(response.getCookies(), nettyResponse.headers().getAll(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)); for (Map.Entry<String, String> header : nettyResponse.headers()) { if (!header.getKey().equalsIgnoreCase(HttpConstants.RESPONSE_COOKIE_HEADER_NAME)) { List<String> values = response.getHeaderValues(header.getKey()); Assert.assertNotNull(values); Assert.assertTrue(values.contains(header.getValue())); } } // make sure the incoming ByteBuf is released Assert.assertEquals(content.refCnt(), 0); ch.finish(); }