List of usage examples for io.netty.channel ChannelFuture channel
Channel channel();
From source file:com.ociweb.pronghorn.adapter.netty.impl.WebSocketServerHandler.java
License:Apache License
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest req) { // Handle a bad request. if (!req.decoderResult().isSuccess()) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST)); return;/*from ww w . j ava 2 s.c om*/ } // Allow only GET methods. if (req.method() != GET) { sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN)); return; } String path = HttpStaticFileServerHandler.sanitizeUri(req.uri(), SystemPropertyUtil.get("user.dir")); System.out.println("path:" + path); if (null != path) { File file = new File(path); if (file.exists() && !file.isHidden()) { try { HttpStaticFileServerHandler.sendFile(ctx, req, file); } catch (ParseException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return; } } // Handshake WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req), null, true); handshaker = wsFactory.newHandshaker(req); if (handshaker == null) { WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel()); } else { GenericFutureListener<ChannelFuture> webSocketIsOpen = new GenericFutureListener<ChannelFuture>() { @Override public void operationComplete(ChannelFuture future) throws Exception { System.out.println("UpgradedWebSocket for id " + future.channel().id().asShortText() + " ||| " + future.channel().id().asLongText() + " thread " + Thread.currentThread().getId()); } }; handshaker.handshake(ctx.channel(), req).addListener(webSocketIsOpen); } }
From source file:com.onion.master.MasterBlockReader.java
License:Apache License
public ByteBuffer readRemoteBlock(InetSocketAddress address, long blockId, long offset, long length) throws IOException { try {//from w w w. j a v a 2 s.com ChannelFuture f = mClientBootstrap.connect(address).sync(); LOG.info("Connected to remote machine {}", address); Channel channel = f.channel(); SingleResponseListener listener = new SingleResponseListener(); mHandler.addListener(listener); channel.writeAndFlush(new RPCBlockReadRequest(blockId, offset, length)); RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS); channel.close().sync(); switch (response.getType()) { case RPC_BLOCK_READ_RESPONSE: RPCBlockReadResponse blockResponse = (RPCBlockReadResponse) response; LOG.info("Data {} from remote machine {} received", blockId, address); RPCResponse.Status status = blockResponse.getStatus(); if (status == RPCResponse.Status.SUCCESS) { // always clear the previous response before reading another one close(); mReadResponse = blockResponse; return blockResponse.getPayloadDataBuffer().getReadOnlyByteBuffer(); } throw new IOException(status.getMessage() + " response: " + blockResponse); case RPC_ERROR_RESPONSE: RPCErrorResponse error = (RPCErrorResponse) response; throw new IOException(error.getStatus().getMessage()); default: throw new IOException(); } } catch (Exception e) { throw new IOException(e); } }
From source file:com.onion.master.MasterBlockWriter.java
License:Apache License
public void write(byte[] bytes, int offset, int length) throws IOException { SingleResponseListener listener = new SingleResponseListener(); try {/*from w w w .ja v a 2 s . c o m*/ // TODO(hy): keep connection open across multiple write calls. ChannelFuture f = mClientBootstrap.connect(mAddress).sync(); LOG.info("Connected to remote machine {}", mAddress); Channel channel = f.channel(); mHandler.addListener(listener); channel.writeAndFlush(new RPCBlockWriteRequest(mSessionId, mBlockId, mWrittenBytes, length, new DataByteArrayChannel(bytes, offset, length))); RPCResponse response = listener.get(NettyClient.TIMEOUT_MS, TimeUnit.MILLISECONDS); channel.close().sync(); switch (response.getType()) { case RPC_BLOCK_WRITE_RESPONSE: RPCBlockWriteResponse resp = (RPCBlockWriteResponse) response; RPCResponse.Status status = resp.getStatus(); LOG.info("status: {} from remote machine {} received", status, mAddress); if (status != RPCResponse.Status.SUCCESS) { throw new IOException(status.getMessage()); } mWrittenBytes += length; break; case RPC_ERROR_RESPONSE: RPCErrorResponse error = (RPCErrorResponse) response; throw new IOException(error.getStatus().getMessage()); default: throw new IOException(); } } catch (Exception e) { throw new IOException(e); } finally { mHandler.removeListener(listener); } }
From source file:com.palace.seeds.net.netty.EchoClient.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w .j a va 2s . c o m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new EchoClientHandler()); } }); // Start the client. ChannelFuture f = b.connect(HOST, PORT).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.phei.netty.chapter10.fileServer.HttpFileServer.java
License:Apache License
public void run(final int port, final String url) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {/*w w w. ja v a 2 s .co m*/ ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder", new HttpRequestDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); ch.pipeline().addLast("http-encoder", new HttpResponseEncoder()); ch.pipeline().addLast("http-chunked", new ChunkedWriteHandler()); ch.pipeline().addLast("fileServerHandler", new HttpFileServerHandler(url)); } }); ChannelFuture future = b.bind("192.168.1.167", port).sync(); System.out.println( "HTTP??? : " + "http://192.168.1.167:" + port + url); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.phei.netty.chapter10.xml.client.HttpXmlClient.java
License:Apache License
public void connect(int port) throws Exception { // ?NIO//from w w w . j av a2 s. com EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-decoder", new HttpResponseDecoder()); ch.pipeline().addLast("http-aggregator", new HttpObjectAggregator(65536)); // XML? ch.pipeline().addLast("xml-decoder", new HttpXmlResponseDecoder(Order.class, true)); ch.pipeline().addLast("http-encoder", new HttpRequestEncoder()); ch.pipeline().addLast("xml-encoder", new HttpXmlRequestEncoder()); ch.pipeline().addLast("xmlClientHandler", new HttpXmlClientHandler()); } }); // ?? ChannelFuture f = b.connect(new InetSocketAddress(port)).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:com.phei.netty.chapter12.netty.client.NettyClient.java
License:Apache License
public void connect(int port, String host) throws Exception { // ?NIO/*from w ww .j a va2 s . c om*/ try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new NettyMessageDecoder(1024 * 1024, 4, 4)); ch.pipeline().addLast("MessageEncoder", new NettyMessageEncoder()); ch.pipeline().addLast("readTimeoutHandler", new ReadTimeoutHandler(50)); ch.pipeline().addLast("LoginAuthHandler", new LoginAuthReqHandler()); ch.pipeline().addLast("HeartBeatHandler", new HeartBeatReqHandler()); } }); // ?? ChannelFuture future = b.connect(new InetSocketAddress(host, port), new InetSocketAddress(NettyConstant.LOCALIP, NettyConstant.LOCAL_PORT)).sync(); future.channel().closeFuture().sync(); } finally { // ???????? executor.execute(() -> { try { TimeUnit.SECONDS.sleep(1); try { connect(NettyConstant.PORT, NettyConstant.REMOTEIP);// ??? } catch (Exception e) { e.printStackTrace(); } } catch (InterruptedException e) { e.printStackTrace(); } }); } }
From source file:com.phei.netty.chapter3.basic.TimeServer.java
License:Apache License
public void bind(int port) throws Exception { // ??NIO//from ww w . j a v a 2 s . c om EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024).childHandler(new ChildChannelHandler()); // ??? ChannelFuture f = b.bind(port).sync(); // ??? f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.phei.netty.codec.msgpack.EchoClient.java
License:Apache License
public void run() throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try {/*from w w w .j a v a 2s .co m*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("msgpack decoder", new MsgpackDecoder()); ch.pipeline().addLast("msgpack encoder", new MsgpackEncoder()); ch.pipeline().addLast(new EchoClientHandler(sendNumber)); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }
From source file:com.phei.netty.codec.msgpack.EchoClientV2.java
License:Apache License
public void run() throws Exception { // Configure the client. EventLoopGroup group = new NioEventLoopGroup(); try {/*w w w.j a v a 2s . c om*/ Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2)); ch.pipeline().addLast("msgpack decoder", new MsgpackDecoder()); ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2)); ch.pipeline().addLast("msgpack encoder", new MsgpackEncoder()); ch.pipeline().addLast(new EchoClientHandler(sendNumber)); } }); // Start the client. ChannelFuture f = b.connect(host, port).sync(); // Wait until the connection is closed. f.channel().closeFuture().sync(); } finally { // Shut down the event loop to terminate all threads. group.shutdownGracefully(); } }