List of usage examples for io.netty.buffer Unpooled copiedBuffer
public static ByteBuf copiedBuffer(ByteBuffer... buffers)
From source file:com.hipishare.chat.securetest.SecureChatClientHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, MsgObject msg) throws Exception { LOG.info("?" + msg.getM()); if (CmdEnum.HEART_BEAT.getCmd() == msg.getC()) { MsgObject msgObj = new MsgObject(); Gson gson = new Gson(); msgObj.setC(CmdEnum.HEART_BEAT.getCmd()); msgObj.setM("o"); String msg2 = gson.toJson(msgObj); ByteBuf buf = Unpooled.copiedBuffer(msg2.getBytes()); ctx.writeAndFlush(buf);//from w ww .j a v a 2 s.c om } }
From source file:com.hipishare.chat.test.EchoClientHandler.java
License:Apache License
/** * Creates a client-side handler.//from w ww .j ava 2s . c om */ public EchoClientHandler() { /*firstMessage = Unpooled.buffer(EchoClient.SIZE); for (int i = 0; i < firstMessage.capacity(); i ++) { firstMessage.writeByte((byte) i); }*/ firstMessage = Unpooled.copiedBuffer("hello".getBytes()); }
From source file:com.hipishare.chat.test.EchoClientHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf buf = (ByteBuf) msg;//w w w. jav a 2s. com int len = buf.readableBytes(); byte[] temp = new byte[len]; ByteBuffer bb = ByteBuffer.allocate(len); buf.readBytes(temp); bb.put(temp); String message = new String(bb.array()); if ("ping".equals(message)) { buf = Unpooled.copiedBuffer(("[id=" + ctx.channel().id() + "]" + "ok").getBytes()); ctx.writeAndFlush(buf); } }
From source file:com.hop.hhxx.example.http2.helloworld.client.Http2Client.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/*from www.j a v a 2 s. c o m*/ SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK; sslCtx = SslContextBuilder.forClient().sslProvider(provider) /* NOTE: the cipher filter may not include all ciphers required by the HTTP/2 specification. * Please refer to the HTTP/2 specification for cipher requirements. */ .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .trustManager(InsecureTrustManagerFactory.INSTANCE) .applicationProtocolConfig(new ApplicationProtocolConfig(Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)) .build(); } else { sslCtx = null; } EventLoopGroup workerGroup = new NioEventLoopGroup(); Http2ClientInitializer initializer = new Http2ClientInitializer(sslCtx, Integer.MAX_VALUE); try { // Configure the client. Bootstrap b = new Bootstrap(); b.group(workerGroup); b.channel(NioSocketChannel.class); b.option(ChannelOption.SO_KEEPALIVE, true); b.remoteAddress(HOST, PORT); b.handler(initializer); // Start the client. Channel channel = b.connect().syncUninterruptibly().channel(); System.out.println("Connected to [" + HOST + ':' + PORT + ']'); // Wait for the HTTP/2 upgrade to occur. Http2SettingsHandler http2SettingsHandler = initializer.settingsHandler(); http2SettingsHandler.awaitSettings(5, TimeUnit.SECONDS); HttpResponseHandler responseHandler = initializer.responseHandler(); int streamId = 3; HttpScheme scheme = SSL ? HttpScheme.HTTPS : HttpScheme.HTTP; AsciiString hostName = new AsciiString(HOST + ':' + PORT); System.err.println("Sending request(s)..."); if (URL != null) { // Create a simple GET request. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, URL); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } if (URL2 != null) { // Create a simple POST request with a body. FullHttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, POST, URL2, Unpooled.copiedBuffer(URL2DATA.getBytes(CharsetUtil.UTF_8))); request.headers().add(HttpHeaderNames.HOST, hostName); request.headers().add(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), scheme.name()); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.GZIP); request.headers().add(HttpHeaderNames.ACCEPT_ENCODING, HttpHeaderValues.DEFLATE); responseHandler.put(streamId, channel.writeAndFlush(request), channel.newPromise()); streamId += 2; } responseHandler.awaitResponses(5, TimeUnit.SECONDS); System.out.println("Finished HTTP/2 request(s)"); // Wait until the connection is closed. channel.close().syncUninterruptibly(); } finally { workerGroup.shutdownGracefully(); } }
From source file:com.ibasco.agql.core.AbstractPacket.java
License:Open Source License
public ByteBuf getPayloadBuffer() { return Unpooled.copiedBuffer(getPayload()); }
From source file:com.intuit.karate.netty.WebSocketClient.java
License:Open Source License
public void sendBytes(byte[] msg) { ByteBuf byteBuf = Unpooled.copiedBuffer(msg); BinaryWebSocketFrame frame = new BinaryWebSocketFrame(byteBuf); channel.writeAndFlush(frame);// www. j a v a 2 s . c o m }
From source file:com.lampard.netty4.frame.fault.TimeServerHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf buf = (ByteBuf) msg;/*from ww w . ja v a2 s . c om*/ byte[] req = new byte[buf.readableBytes()]; buf.readBytes(req); String body = new String(req, "UTF-8").substring(0, req.length - System.getProperty("line.separator").length()); System.out.println("The time server receive order : " + body + " ; the counter is : " + ++counter); String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(body) ? new java.util.Date(System.currentTimeMillis()).toString() : "BAD ORDER"; currentTime = currentTime + System.getProperty("line.separator"); ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes()); ctx.writeAndFlush(resp); }
From source file:com.lbwan.game.client.WebSocketClientRunner.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {/*ww w. j a v a 2 s . com*/ // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 or V00. // If you change it to V00, ping is not supported and remember to change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the pipeline. final WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); final String protocol = uri.getScheme(); int defaultPort; ChannelInitializer<SocketChannel> initializer; // Normal WebSocket if ("ws".equals(protocol)) { initializer = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-codec", new HttpClientCodec()) .addLast("aggregator", new HttpObjectAggregator(8192)) .addLast("ws-handler", handler); } }; defaultPort = 80; // Secure WebSocket } else { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(initializer); int port = uri.getPort(); // If no port was specified, we'll try the default port: https://tools.ietf.org/html/rfc6455#section-1.7 if (uri.getPort() == -1) { port = defaultPort; } Channel ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); BufferedReader console = new BufferedReader(new InputStreamReader(System.in)); while (true) { String msg = console.readLine(); if (msg == null) { break; } else if ("bye".equals(msg.toLowerCase())) { ch.writeAndFlush(new CloseWebSocketFrame()); ch.closeFuture().sync(); break; } else if ("ping".equals(msg.toLowerCase())) { WebSocketFrame frame = new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 8, 1, 8, 1 })); ch.writeAndFlush(frame); } else { WebSocketFrame frame = new TextWebSocketFrame(msg); ch.writeAndFlush(frame); } } } finally { group.shutdownGracefully(); } }
From source file:com.liferay.sync.engine.lan.server.discovery.LanDiscoveryBroadcaster.java
License:Open Source License
public void broadcast(int port) throws Exception { if ((_channel == null) || !_channel.isActive()) { _initialize();//from w w w . j a v a 2 s .c o m } byte[] bytes = JSONUtil.writeValueAsBytes(LanClientUtil.createSyncLanClient(port)); DatagramPacket datagramPacket = new DatagramPacket(Unpooled.copiedBuffer(bytes), new InetSocketAddress("255.255.255.255", PropsValues.SYNC_LAN_SERVER_PORT)); ChannelFuture channelFuture = _channel.writeAndFlush(datagramPacket); channelFuture.sync(); }
From source file:com.linecorp.armeria.internal.PooledObjects.java
License:Apache License
private static <T> T copyAndRelease(ByteBuf o) { try {//w w w . j av a2 s . com @SuppressWarnings("unchecked") final T copy = (T) Unpooled.copiedBuffer(o); return copy; } finally { ReferenceCountUtil.safeRelease(o); } }