io.netty.channel.socket.nio.NioSocketChannel Java Examples

The following examples show how to use io.netty.channel.socket.nio.NioSocketChannel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: EchoTest.java    From jdk-source-analysis with Apache License 2.0 6 votes vote down vote up
@Test
public void testClient() throws InterruptedException {
  NioEventLoopGroup group = new NioEventLoopGroup();
  try {
    Bootstrap b = new Bootstrap();
    b.group(group)
      .channel(NioSocketChannel.class)
      .remoteAddress(new InetSocketAddress("localhost", PORT))
      .handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
          ch.pipeline().addLast(new EchoClientHandler());
        }
      });
    ChannelFuture f = b.connect().sync();
    f.channel().closeFuture().sync();
  } finally {
    group.shutdownGracefully().sync();
  }
}
 
Example #2
Source File: UpdaterClient.java    From MercuryTrade with MIT License 6 votes vote down vote up
public void start() {
    ClientChannelInitializer clientChannelInitializer = new ClientChannelInitializer();
    group = new NioEventLoopGroup();
    bootstrap = new Bootstrap();
    bootstrap.group(group).channel(NioSocketChannel.class)
            .remoteAddress(new InetSocketAddress(host, port))
            .option(ChannelOption.SO_KEEPALIVE, true)
            .handler(clientChannelInitializer)
    ;
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    doConnect();
}
 
Example #3
Source File: NettyServerClient.java    From PeonyFramwork with Apache License 2.0 6 votes vote down vote up
public NettyServerClient(int serverType,int serverId, String host, int port) {
    this.serverType = serverType;
    this.serverId = serverId;
    this.address = new InetSocketAddress(host, port);

    netEventService = BeanHelper.getServiceBean(NetEventService.class);
    eventService = BeanHelper.getServiceBean(EventService.class);

    bootstrap = new Bootstrap(); // (1)
    bootstrap.group(eventLoopGroup); // (2)
    bootstrap.channel(NioSocketChannel.class); // (3)
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true); // (4)
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(
                    new DefaultNettyEncoder(),
                    new DefaultNettyDecoder(),
                    new NettyClientHandler()
            );
        }
    });
}
 
Example #4
Source File: NettyHttpClient.java    From mpush with Apache License 2.0 6 votes vote down vote up
@Override
protected void doStart(Listener listener) throws Throwable {
    workerGroup = new NioEventLoopGroup(http_work, new DefaultThreadFactory(ThreadNames.T_HTTP_CLIENT));
    b = new Bootstrap();
    b.group(workerGroup);
    b.channel(NioSocketChannel.class);
    b.option(ChannelOption.SO_KEEPALIVE, true);
    b.option(ChannelOption.TCP_NODELAY, true);
    b.option(ChannelOption.SO_REUSEADDR, true);
    b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 4000);
    b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
    b.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("decoder", new HttpResponseDecoder());
            ch.pipeline().addLast("aggregator", new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast("encoder", new HttpRequestEncoder());
            ch.pipeline().addLast("handler", new HttpClientHandler(NettyHttpClient.this));
        }
    });
    timer = new HashedWheelTimer(new NamedThreadFactory(T_HTTP_TIMER), 1, TimeUnit.SECONDS, 64);
    listener.onSuccess();
}
 
Example #5
Source File: ProxyClient.java    From proxy with MIT License 6 votes vote down vote up
/**
 * 初始化 连接后端真正服务器
 */
private void initRealServerBoot() {

    //初始化
    realServerBootstrap = new Bootstrap();
    realServerGroup = new NioEventLoopGroup();


    realServerBootstrap.group(realServerGroup);
    realServerBootstrap.channel(NioSocketChannel.class);
    realServerBootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new TCPHandler());
            ch.pipeline().addLast(new HttpResponseDecoder());
            ch.pipeline().addLast(new HttpObjectAggregator(maxContentLength));
            ch.pipeline().addLast(new HttpSendHandler());
        }
    });
}
 
Example #6
Source File: FlowControlHandlerTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static Channel newClient(SocketAddress server) {
    Bootstrap bootstrap = new Bootstrap();

    bootstrap.group(GROUP)
        .channel(NioSocketChannel.class)
        .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 1000)
        .handler(new ChannelInboundHandlerAdapter() {
            @Override
            public void channelRead(ChannelHandlerContext ctx, Object msg) {
                fail("In this test the client is never receiving a message from the server.");
            }
        });

    return bootstrap.connect(server)
            .syncUninterruptibly()
            .channel();
}
 
Example #7
Source File: GpbTcpServer.java    From Okra with Apache License 2.0 6 votes vote down vote up
@Override
    protected ChannelHandler newChannelInitializer() {
        return new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ChannelPipeline cp = ch.pipeline();
                cp.addLast("frame", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2));
                cp.addLast("prepender", FRAME_PREPENDER);
                cp.addLast("decoder", GPB_DECODER_HANDLER);
                cp.addLast("encoder", GPB_ENCODER_HANDLER);
                // handler
                cp.addLast("handler", serverHandler);
//                cp.addLast("handler", new ServerHandler());
            }
        };
    }
 
Example #8
Source File: OzymandiasClient.java    From archistar-core with GNU General Public License v2.0 6 votes vote down vote up
@SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
private Channel connectServer(int port) throws Exception {

    final OzymandiasClientHandler handler = new OzymandiasClientHandler(this);

    Bootstrap b = new Bootstrap();
    b.group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    SSLEngine engine = SSLContextFactory.getClientContext().createSSLEngine();
                    engine.setUseClientMode(true);

                    ch.pipeline().addLast(
                            new SslHandler(engine),
                            new ObjectEncoder(),
                            new ObjectDecoder(OzymandiasServer.maxObjectSize, ClassResolvers.cacheDisabled(null)),
                            handler);
                }
            });

    return b.connect("127.0.0.1", port).sync().channel();
}
 
Example #9
Source File: KQueueSocketTestPermutation.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public List<BootstrapFactory<Bootstrap>> clientSocket() {
    return Arrays.asList(
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(KQUEUE_WORKER_GROUP).channel(KQueueSocketChannel.class);
                }
            },
            new BootstrapFactory<Bootstrap>() {
                @Override
                public Bootstrap newInstance() {
                    return new Bootstrap().group(nioWorkerGroup).channel(NioSocketChannel.class);
                }
            }
    );
}
 
Example #10
Source File: NettyNioAsyncHttpClientWireMockTest.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void responseConnectionReused_shouldReleaseChannel() throws Exception {

    ChannelFactory channelFactory = mock(ChannelFactory.class);
    EventLoopGroup customEventLoopGroup = new NioEventLoopGroup(1);
    NioSocketChannel channel = new NioSocketChannel();

    when(channelFactory.newChannel()).thenAnswer((Answer<NioSocketChannel>) invocationOnMock -> channel);
    SdkEventLoopGroup eventLoopGroup = SdkEventLoopGroup.create(customEventLoopGroup, channelFactory);

    NettyNioAsyncHttpClient customClient =
        (NettyNioAsyncHttpClient) NettyNioAsyncHttpClient.builder()
                                                         .eventLoopGroup(eventLoopGroup)
                                                         .maxConcurrency(1)
                                                         .build();

    makeSimpleRequest(customClient);
    verifyChannelRelease(channel);
    assertThat(channel.isShutdown()).isFalse();

    customClient.close();
    eventLoopGroup.eventLoopGroup().shutdownGracefully().awaitUninterruptibly();
}
 
Example #11
Source File: NettyServer.java    From ClusterDeviceControlPlatform with MIT License 6 votes vote down vote up
public void start() {
    new Thread(() -> {
        group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .remoteAddress(new InetSocketAddress(30232)) //"woodswang",
                .handler(KyChannelInitializer.newInstance());
        ChannelFuture channelFuture = null;

        try {
            channelFuture = bootstrap.connect().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        startListenerHandle(channelFuture, launchListener);
    }).start();
}
 
Example #12
Source File: NettyClient.java    From dubbo3 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    com.alibaba.dubbo.remoting.transport.netty4.NettyHelper.setNettyLoggerFactory();
    bootstrap = new Bootstrap();
    // config
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(WORKER_GROUP);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
    final com.alibaba.dubbo.remoting.transport.netty4.NettyHandler nettyHandler = new com.alibaba.dubbo.remoting.transport.netty4.NettyHandler(getUrl(), this);
    bootstrap.handler(new ChannelInitializer() {
        public void initChannel(Channel ch) {
            com.alibaba.dubbo.remoting.transport.netty4.NettyCodecAdapter adapter = new com.alibaba.dubbo.remoting.transport.netty4.NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline channelPipeline = ch.pipeline();
            channelPipeline.addLast("decoder", adapter.getDecoder());
            channelPipeline.addLast("encoder", adapter.getEncoder());
            channelPipeline.addLast("handler", nettyHandler);
        }
    });

}
 
Example #13
Source File: ChannelMediator.java    From flashback with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Establishing TCP connection to server
 *
 * @param remoteAddress remote address
 * */
public ChannelFuture connectToServer(final InetSocketAddress remoteAddress) {
  if (remoteAddress == null) {
    throw new IllegalStateException("remote address is null");
  }
  Bootstrap bootstrap = new Bootstrap().group(_upstreamWorkerGroup);
  bootstrap.channelFactory(NioSocketChannel::new);
  ServerChannelHandler serverChannelHandler = new ServerChannelHandler(this);

  bootstrap.handler(new ChannelInitializer<Channel>() {
    protected void initChannel(Channel ch)
        throws Exception {
      initChannelPipeline(ch.pipeline(), serverChannelHandler, _serverConnectionIdleTimeoutMsec);
      _serverChannel = ch;
    }
  });
  LOG.debug("Server channel is ready. About to connect....");
  return bootstrap.connect(remoteAddress);
}
 
Example #14
Source File: PsyncLatencyTest.java    From x-pipe with Apache License 2.0 6 votes vote down vote up
private void startSendMessage() {

		EventLoopGroup eventLoopGroup = new NioEventLoopGroup(); 
        Bootstrap b = new Bootstrap();
        b.group(eventLoopGroup)
         .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 LoggingHandler(LogLevel.DEBUG));
                 p.addLast(new NettySimpleMessageHandler());
                 p.addLast(new SetMessageHandler(PsyncLatencyTest.this));
             }
         });
        b.connect(master);
	}
 
Example #15
Source File: NettyThreadManager.java    From fastjgame with Apache License 2.0 6 votes vote down vote up
/**
 * 异步建立连接localHost
 *
 * @param hostAndPort      服务器地址
 * @param sndBuffer        socket发送缓冲区
 * @param rcvBuffer        socket接收缓冲区
 * @param connectTimeoutMs 建立连接超时时间
 * @param initializer      channel初始化类,根据使用的协议(eg:tcp,ws) 和 序列化方式(eg:json,protoBuf)确定
 * @return channelFuture 注意使用{@link ChannelFuture#sync()} 会抛出异常。
 * 使用{@link ChannelFuture#await()} 和{@link ChannelFuture#isSuccess()} 安全处理。
 * 此外,使用channel 需要调用 {@link Channel#isActive()}检查是否成功和远程建立连接
 */
public ChannelFuture connectAsyn(HostAndPort hostAndPort, int sndBuffer, int rcvBuffer, int connectTimeoutMs,
                                 ChannelInitializer<SocketChannel> initializer) {
    Bootstrap bootstrap = new Bootstrap();
    bootstrap.group(workerGroup);

    bootstrap.channel(NioSocketChannel.class);
    bootstrap.handler(initializer);

    bootstrap.option(ChannelOption.SO_KEEPALIVE, false);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_SNDBUF, sndBuffer);
    bootstrap.option(ChannelOption.SO_RCVBUF, rcvBuffer);
    bootstrap.option(ChannelOption.SO_LINGER, 0);
    bootstrap.option(ChannelOption.SO_REUSEADDR, true);
    bootstrap.option(ChannelOption.WRITE_BUFFER_WATER_MARK, WRITE_BUFFER_WATER_MARK);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs);
    return bootstrap.connect(hostAndPort.getHost(), hostAndPort.getPort());
}
 
Example #16
Source File: NettyClient.java    From dubbo-remoting-netty4 with Apache License 2.0 6 votes vote down vote up
@Override
protected void doOpen() throws Throwable {
    NettyHelper.setNettyLoggerFactory();
    bootstrap = new Bootstrap();
    // config
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.group(WORKER_GROUP);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, getTimeout());
    final NettyHandler nettyHandler = new NettyHandler(getUrl(), this);
    bootstrap.handler(new ChannelInitializer() {
        public void initChannel(Channel ch) {
            NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this);
            ChannelPipeline channelPipeline = ch.pipeline();
            channelPipeline.addLast("decoder", adapter.getDecoder());
            channelPipeline.addLast("encoder", adapter.getEncoder());
            channelPipeline.addLast("handler", nettyHandler);
        }
    });

}
 
Example #17
Source File: ChannelConfiguration.java    From xio with Apache License 2.0 6 votes vote down vote up
/**
 * This method will configure a worker EventLoopGroup and a Channel for use by a client. It will
 * try to use the correct SocketChannel for the provided workerGroup.
 *
 * @param workerGroup uses EventLoopGroup in the ClientChannelConfiguration
 * @return ClientChannelConfiguration
 */
public static ClientChannelConfiguration clientConfig(EventLoopGroup workerGroup) {
  EventLoopGroup parent = workerGroup;
  if (parent instanceof EventLoop) {
    parent = ((EventLoop) workerGroup).parent();
  }
  Class<? extends Channel> channelClass;
  if (parent instanceof EpollEventLoopGroup) {
    channelClass = EpollSocketChannel.class;
  } else if (parent instanceof NioEventLoopGroup) {
    channelClass = NioSocketChannel.class;
  } else {
    throw new RuntimeException("Unsupported EventLoopGroup " + workerGroup.getClass());
  }

  return new ClientChannelConfiguration(workerGroup, channelClass);
}
 
Example #18
Source File: ConnectionService.java    From p2p with Apache License 2.0 6 votes vote down vote up
public void connectTo(final Peer peer, final String host, final int port, final CompletableFuture<Void> futureToNotify) {
    final PeerChannelHandler handler = new PeerChannelHandler(config, peer);
    final PeerChannelInitializer initializer = new PeerChannelInitializer(config, encoder, peerEventLoopGroup, handler);
    final Bootstrap clientBootstrap = new Bootstrap();
    clientBootstrap.group(networkEventLoopGroup).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true)
            .handler(initializer);

    final ChannelFuture connectFuture = clientBootstrap.connect(host, port);
    if (futureToNotify != null) {
        connectFuture.addListener(new ChannelFutureListener() {
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    futureToNotify.complete(null);
                    LOGGER.info("Successfully connect to {}:{}", host, port);
                } else {
                    futureToNotify.completeExceptionally(future.cause());
                    LOGGER.error("Could not connect to " + host + ":" + port, future.cause());
                }
            }
        });
    }
}
 
Example #19
Source File: TrafficSimulationTests.java    From nano-proxy with Apache License 2.0 6 votes vote down vote up
public void connect(String host, int port) throws Exception{
this.bootstrap = new Bootstrap();
final CountDownLatch latch = new CountDownLatch(1);
bootstrap.group(new NioEventLoopGroup(1))
		.channel(NioSocketChannel.class)
		.handler(new TrafficGeneratorClientHandler());
	System.out.println("Creating connection");
	ChannelFuture cf = bootstrap.connect(host,port);
	cf.addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(ChannelFuture future) throws Exception {
			System.out.println("Connected");
			if (future.isSuccess()) {
				channel = future.channel();
			} else {
				future.cause().printStackTrace();
				future.channel().close();
				throw new RuntimeException(future.cause());
			}
			latch.countDown();
		}
	});
latch.await();
}
 
Example #20
Source File: NettyClient.java    From netty-learning-example with Apache License 2.0 6 votes vote down vote up
/**
 * 重连
 */
public void doConnect(Bootstrap bootstrap, EventLoopGroup eventLoopGroup) {
    try {
        if (bootstrap != null) {
            bootstrap.group(eventLoopGroup);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.handler(new NettyClientInitializer());
            bootstrap.remoteAddress(host, port);
            f = bootstrap.connect().addListener((ChannelFuture futureListener) -> {
                final EventLoop eventLoop = futureListener.channel().eventLoop();
                if (!futureListener.isSuccess()) {
                    log.info("与服务端断开连接!在10s之后准备尝试重连!");
                    eventLoop.schedule(() -> doConnect(new Bootstrap(), eventLoop), 10, TimeUnit.SECONDS);
                }
            });
            if(initFalg){
                log.info("Netty客户端启动成功!");
                initFalg=false;
            }
        }
    } catch (Exception e) {
        log.info("客户端连接失败!"+e.getMessage());
    }

}
 
Example #21
Source File: BootstrapTemplate.java    From netty-cookbook with Apache License 2.0 6 votes vote down vote up
public static void newClientBootstrap(String host, int port, ChannelInitializer<SocketChannel> initializer){
	EventLoopGroup group = new NioEventLoopGroup();
       try {
           Bootstrap b = new Bootstrap();
           ChannelFuture f = b.group(group)
           		.channel(NioSocketChannel.class)
           		.option(ChannelOption.SO_KEEPALIVE, true)
           		.handler(new LoggingHandler(LogLevel.INFO))
           		.handler(initializer)
           		.connect(host, port).sync();            
           f.channel().closeFuture().sync();            
       } catch (Exception e){   
           e.printStackTrace();
       } finally {        	
           group.shutdownGracefully();
       }
}
 
Example #22
Source File: HttpClient.java    From InChat with Apache License 2.0 6 votes vote down vote up
private HttpClient(){
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(workerGroup);
        b.channel(NioSocketChannel.class);
        b.option(ChannelOption.SO_KEEPALIVE, true);
        b.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
            // 客户端接收到的是httpResponse响应,所以要使用HttpResponseDecoder进行解码
            ch.pipeline().addLast(new HttpResponseDecoder());
            // 客户端发送的是httprequest,所以要使用HttpRequestEncoder进行编码
            ch.pipeline().addLast(new HttpRequestEncoder());
            try {
                SSLContext context = SslUtil.createSSLContext("JKS","inchat.jks","123456");
                SSLEngine engine = context.createSSLEngine();
                engine.setUseClientMode(true);
//                engine.setNeedClientAuth(false);
                ch.pipeline().addLast("ssl",new SslHandler(engine));
            }catch (Exception e){
                e.printStackTrace();
            }
            }
        });
        this.bootstrap = b;
    }
 
Example #23
Source File: TrafficSimulationTests.java    From nano-proxy with Apache License 2.0 6 votes vote down vote up
@Test
public void simple() throws Exception {
	Bootstrap bootstrap = new Bootstrap();
	bootstrap.group(new NioEventLoopGroup(1))
			.channel(NioSocketChannel.class)
			.handler(new TrafficGeneratorClientHandler());
	final CountDownLatch latch = new CountDownLatch(1);
	bootstrap.connect("localhost",8010).addListener(new ChannelFutureListener() {
		@Override
		public void operationComplete(ChannelFuture future) throws Exception {
			if(future.isSuccess()){
				future.channel().writeAndFlush(Unpooled.buffer().capacity(256).writeZero(256));
			}else {
				System.err.println("Connection attempt failed");
				future.cause().printStackTrace();
			}
			latch.countDown();
		}
	});

latch.await();

}
 
Example #24
Source File: AbstractServer.java    From panama with MIT License 6 votes vote down vote up
@Override
public void start(int maxThread) {
    EventLoopGroup mainGroup = new NioEventLoopGroup(1);
    EventLoopGroup workGroup = new NioEventLoopGroup(maxThread);

    ServerBootstrap serverBootstrap = new ServerBootstrap();
    serverBootstrap.group(mainGroup, workGroup).
            channel(NioServerSocketChannel.class).
            childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel ch) throws Exception {
                    setupPipeline(ch.pipeline());
                }
            });
    try {
        serverChannel = serverBootstrap.bind(port).sync().channel();
        serverChannel.closeFuture().sync();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #25
Source File: UptimeClient.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new NioEventLoopGroup();
    bs.group(group)
            .channel(NioSocketChannel.class)
            .remoteAddress(HOST, PORT)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new IdleStateHandler(READ_TIMEOUT, 0, 0), handler);
                }
            });
    bs.connect();
}
 
Example #26
Source File: BenchmarkServer.java    From Okra with Apache License 2.0 5 votes vote down vote up
@Override
protected ChannelHandler newChannelInitializer() {
    return new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel ch) throws Exception {
                ChannelPipeline cp = ch.pipeline();
                cp.addLast("frame", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 2, 0, 2));
                cp.addLast("prepender", FRAME_PREPENDER);
                // Any other useful handler
                cp.addLast("strDecoder", STRING_DECODER);
                cp.addLast("strEncoder", STRING_ENCODER);
                cp.addLast("handler", HANDLER);
            }
    };
}
 
Example #27
Source File: RPCClient.java    From rpc-java with Apache License 2.0 5 votes vote down vote up
private void init(RPCClientOptions options) {
    Validate.notNull(options);
    this.rpcClientOptions = options;
    pendingRPC = new ConcurrentHashMap<Long, RPCFuture>();
    timeoutTimer = Executors.newScheduledThreadPool(1,
            new CustomThreadFactory("timeout-timer-thread"));
    this.endPoints = new CopyOnWriteArrayList<EndPoint>();
    this.allConnections = new CopyOnWriteArrayList<RPCChannelGroup>();

    // init netty bootstrap
    bootstrap = new Bootstrap();
    bootstrap.channel(NioSocketChannel.class);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, rpcClientOptions.getConnectTimeoutMillis());
    bootstrap.option(ChannelOption.SO_KEEPALIVE, rpcClientOptions.isKeepAlive());
    bootstrap.option(ChannelOption.SO_REUSEADDR, rpcClientOptions.isReuseAddr());
    bootstrap.option(ChannelOption.TCP_NODELAY, rpcClientOptions.isTCPNoDelay());
    bootstrap.option(ChannelOption.SO_RCVBUF, rpcClientOptions.getReceiveBufferSize());
    bootstrap.option(ChannelOption.SO_SNDBUF, rpcClientOptions.getSendBufferSize());
    ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast(new RPCRequestEncoder(RPCClient.this));
            ch.pipeline().addLast(new RPCResponseDecoder(RPCClient.this));
            ch.pipeline().addLast(new RPCClientHandler(RPCClient.this));
        }
    };
    bootstrap.group(new NioEventLoopGroup(
            options.getIoThreadNum(),
            new CustomThreadFactory("client-io-thread")))
            .handler(initializer);
}
 
Example #28
Source File: WebSocketIT.java    From timely with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    s = new Server(conf);
    s.run();

    Connector con = mac.getConnector("root", "secret");
    con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));

    this.sessionId = UUID.randomUUID().toString();
    AuthCache.put(sessionId, TimelyPrincipal.anonymousPrincipal());
    group = new NioEventLoopGroup();
    SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(HttpHeaderNames.COOKIE, cookieVal);

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
            WebSocketVersion.V13, (String) null, false, headers);
    handler = new ClientHandler(handshaker);
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(8192));
            ch.pipeline().addLast(handler);
        }
    });
    ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
    // Wait until handshake is complete
    while (!handshaker.isHandshakeComplete()) {
        sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        LOG.debug("Waiting for Handshake to complete");
    }
}
 
Example #29
Source File: BuilderUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the correct {@link Class} to use with the given {@link EventLoopGroup}.
 *
 * @param group        the {@link EventLoopGroup} for which the class is needed
 * @param addressClass The class of the address that to connect to.
 * @return the class that should be used for bootstrapping
 */
public static Class<? extends Channel> socketChannel(EventLoopGroup group,
                                                     Class<? extends SocketAddress> addressClass) {
    if (useEpoll(group)) {
        return DomainSocketAddress.class.isAssignableFrom(addressClass) ? EpollDomainSocketChannel.class :
                EpollSocketChannel.class;
    } else if (useKQueue(group)) {
        return DomainSocketAddress.class.isAssignableFrom(addressClass) ? KQueueDomainSocketChannel.class :
                KQueueSocketChannel.class;
    } else {
        return NioSocketChannel.class;
    }
}
 
Example #30
Source File: FastdfsPoolGroup.java    From azeroth with Apache License 2.0 5 votes vote down vote up
@Override
protected FastdfsPool newPool(InetSocketAddress addr) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("channel pool created : {}", addr);
    }

    Bootstrap bootstrap = new Bootstrap().channel(NioSocketChannel.class).group(loopGroup);
    bootstrap.remoteAddress(addr);
    bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) connectTimeout);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);
    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    return new FastdfsPool(bootstrap, readTimeout, idleTimeout, maxConnPerHost);
}