Search in sources :

Example 1 with HelloClient

use of org.ko.netty.tn.handler.HelloClient in project tutorials-java by Artister.

the class NettyClient method run.

public void run() {
    EventLoopGroup group = new NioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group);
        b.channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true);
        b.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
                pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
                pipeline.addLast("frameEncoder", new LengthFieldPrepender(4));
                pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
                pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
                pipeline.addLast("handler", new HelloClient());
            }
        });
        for (int i = 0; i < 10; i++) {
            ChannelFuture f = b.connect("127.0.0.1", 5656).sync();
            f.channel().writeAndFlush("hello Service!" + Thread.currentThread().getName() + ":--->:" + i);
            f.channel().closeFuture().sync();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        group.shutdownGracefully();
    }
}
Also used : NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) SocketChannel(io.netty.channel.socket.SocketChannel) HelloClient(org.ko.netty.tn.handler.HelloClient) StringDecoder(io.netty.handler.codec.string.StringDecoder) LengthFieldPrepender(io.netty.handler.codec.LengthFieldPrepender) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) StringEncoder(io.netty.handler.codec.string.StringEncoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) Bootstrap(io.netty.bootstrap.Bootstrap) LengthFieldBasedFrameDecoder(io.netty.handler.codec.LengthFieldBasedFrameDecoder) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup)

Aggregations

Bootstrap (io.netty.bootstrap.Bootstrap)1 NioEventLoopGroup (io.netty.channel.nio.NioEventLoopGroup)1 SocketChannel (io.netty.channel.socket.SocketChannel)1 NioSocketChannel (io.netty.channel.socket.nio.NioSocketChannel)1 LengthFieldBasedFrameDecoder (io.netty.handler.codec.LengthFieldBasedFrameDecoder)1 LengthFieldPrepender (io.netty.handler.codec.LengthFieldPrepender)1 StringDecoder (io.netty.handler.codec.string.StringDecoder)1 StringEncoder (io.netty.handler.codec.string.StringEncoder)1 HelloClient (org.ko.netty.tn.handler.HelloClient)1