Java Code Examples for io.netty.handler.codec.string.StringDecoder

The following are top voted examples for showing how to use io.netty.handler.codec.string.StringDecoder. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: neto   File: ProtocolUnificationHandler.java   View source code 6 votes vote down vote up
private void switchToBinary(ChannelHandlerContext ctx) {
    ChannelPipeline p = ctx.pipeline();
    p.addLast(new DelimiterBasedFrameDecoder(maxFrameLength, Delimiters.lineDelimiter()));
    p.addLast(new StringDecoder(Charset.forName(charset)));
    p.addLast(new NetoJsonToMessageDecoder(opcodeMap));

    NetoMessageToJsonEncoder netoMessageToJsonEncoder = new NetoMessageToJsonEncoder();
    netoMessageToJsonEncoder.setOpcodeMap(opcodeMap);

    p.addLast(netoMessageToJsonEncoder);
    p.addLast(new MessageHandler(redisService));
    p.remove(this);


    // 핸들러를 다시 등록 했으므로 이벤트를 전파
    ctx.fireChannelActive();
}
 
Example 2
Project: neto   File: ChannelServerInitializer.java   View source code 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {

    NetoJsonToMessageDecoder decoder = new NetoJsonToMessageDecoder(opcodeMap);
    NetoMessageToJsonEncoder encoder = new NetoMessageToJsonEncoder();

    if (opcodeMap instanceof BiMap) {
        encoder.setOpcodeMap((BiMap<Integer, Class<? extends NetoJsonMessage>>) opcodeMap);
    }

    MessageHandler handler = new MessageHandler(redisService);

    ChannelPipeline p = ch.pipeline();

    p.addLast(new DelimiterBasedFrameDecoder(maxFrameLength, Delimiters.lineDelimiter()));
    p.addLast(new StringDecoder(Charset.forName(charset)));
    p.addLast(decoder);
    p.addLast(encoder);
    p.addLast(handler);
}
 
Example 3
Project: neto   File: SecureChatClientInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    pipeline.addLast(new LoggingHandler());
    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    if (sslCtx != null)
        pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatClientHandler());
}
 
Example 4
Project: jfast   File: ServerTest.java   View source code 6 votes vote down vote up
@Test
public void serverBootStrapWithOptionsTest() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
	LinkedHashMap<String, Object> channelHandlerOptions = new LinkedHashMap<String, Object>();
	
	channelHandlerOptions.put("lineFrame", new LineBasedFrameDecoder(2000));
	channelHandlerOptions.put("decoder", new StringDecoder());
	channelHandlerOptions.put("encoder", new StringEncoder());
	channelHandlerOptions.put("handler", new ChannelInboundHandlerAdapter() {
		
		@Override
		public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
			log.info("Message Received and forward to ConsumerProcessor. Msg -> {}", msg);
		}
	});
	
	Server server = BootStrap.builder()
			.port(5252)
			.options(channelHandlerOptions)
			.messageConsumer(msg -> log.info(msg))
			.build();
	
	assertNotNull(server);
}
 
Example 5
Project: AlphaLibary   File: EchoClient.java   View source code 6 votes vote down vote up
public EchoClient(String host, int port) {
    EventLoopGroup worker = new NioEventLoopGroup();

    Bootstrap b = new Bootstrap();

    b.group(worker)
            .channel(NioSocketChannel.class)
            .option(ChannelOption.SO_KEEPALIVE, true)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) {
                    socketChannel.pipeline()
                            .addLast(new StringDecoder())
                            .addLast(new StringEncoder())
                            .addLast(ech);
                }
            });

    b.connect(host, port);
}
 
Example 6
Project: java_learn   File: TimeClient.java   View source code 6 votes vote down vote up
public void connect(int port, String host) throws InterruptedException {
	
	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
			protected void initChannel(SocketChannel ch) throws Exception {
				ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
				ch.pipeline().addLast(new StringDecoder());
				ch.pipeline().addLast(new TimeClientHandler());
			}
			
		});
		
		//发送异步链接操作
		ChannelFuture f = b.connect(host, port).sync();
		//等待客户端链路关闭
		f.channel().closeFuture().sync();
	}finally{
		group.shutdownGracefully();
	}
	
}
 
Example 7
Project: raft-java   File: StartServer.java   View source code 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
	ch.config().setAllowHalfClosure(true);
	ChannelPipeline pipeline = ch.pipeline();

	//IdleStateHandler 与客户端链接后,根据超出配置的时间自动触发userEventTriggered
	//readerIdleTime服务端长时间没有读到数据,则为读空闲,触发读空闲监听,并自动关闭链路连接,周期性按readerIdleTime的超时间触发空闲监听方法
	//writerIdleTime服务端长时间没有发送写请求,则为空闲,触发写空闲监听,空闲期间,周期性按writerIdleTime的超时间触发空闲监听方法
	//allIdleTime 服务端在allIdleTime时间内未接收到客户端消息,或者,也未去向客户端发送消息,则触发周期性操作
	pipeline.addLast("ping", new IdleStateHandler(10, 20, 35, TimeUnit.SECONDS));
	// 以("\n")为结尾分割的 解码器
	pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
	// 字符串解码 和 编码
	pipeline.addLast("decoder", new StringDecoder());
	pipeline.addLast("encoder", new StringEncoder());
	// 自己的逻辑Handler
	pipeline.addLast("handler", new DataServerHandler(nodeInfo));
}
 
Example 8
Project: raft-java   File: StartServer.java   View source code 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
	ch.config().setAllowHalfClosure(true);
	ChannelPipeline pipeline = ch.pipeline();

	//IdleStateHandler 与客户端链接后,根据超出配置的时间自动触发userEventTriggered
	//readerIdleTime服务端长时间没有读到数据,则为读空闲,触发读空闲监听,并自动关闭链路连接,周期性按readerIdleTime的超时间触发空闲监听方法
	//writerIdleTime服务端长时间没有发送写请求,则为空闲,触发写空闲监听,空闲期间,周期性按writerIdleTime的超时间触发空闲监听方法
	//allIdleTime 服务端在allIdleTime时间内未接收到客户端消息,或者,也未去向客户端发送消息,则触发周期性操作
	pipeline.addLast("ping", new IdleStateHandler(10, 20, 35, TimeUnit.SECONDS));
	// 以("\n")为结尾分割的 解码器
	pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
	// 字符串解码 和 编码
	pipeline.addLast("decoder", new StringDecoder());
	pipeline.addLast("encoder", new StringEncoder());
	// 自己的逻辑Handler
	pipeline.addLast("handler", new ElectionServerHandler(nodeInfo));
}
 
Example 9
Project: netty-tutorials   File: NettyClient.java   View source code 6 votes vote down vote up
public void connect(String host, int port) throws InterruptedException {
    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
                    protected void initChannel(SocketChannel ch) throws Exception {

                        ch.pipeline().addLast(new FixedLengthFrameDecoder(1<<5));
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new StringEncoder());

                        ch.pipeline().addLast(new ClientHandler());
                    }
                });

        ChannelFuture future = b.connect(host, port).sync();

        future.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 10
Project: bookish-meme   File: ChatServerInitializer.java   View source code 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
    ChannelPipeline pipeline = socketChannel.pipeline();
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()))
            .addLast("decoder", new StringDecoder())
            .addLast("encoder", new StringEncoder())
            .addLast("json_to_ob",new JsonToObjectHandler())
            .addLast("register",new RegisterHandler())
            .addLast("authority", new AuthorityHandler())
            .addLast("enterGroup",new EnterGroupHandler())
            .addLast("channelManager", new ChannelManagerHandler())
            .addLast("createGroup", new CreateGroupHandler())
            .addLast("addGroup", new AddGroupHandler())
            .addLast("deleteGroup",new DeleteGroupHandler())
            .addLast("Limiter", new LimiterHandler())
            .addLast("log", new LoggerHandler())
            .addLast("response", new Responser());
}
 
Example 11
Project: JavaAyo   File: HelloClientInitializer.java   View source code 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    /*
     * 这个地方的 必须和服务端对应上。否则无法正常解码和编码
     * 
     * 解码和编码 我将会在下一张为大家详细的讲解。再次暂时不做详细的描述
     */
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192,
            Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    // 客户端的逻辑
    pipeline.addLast("handler", new HelloClientHandler());
}
 
Example 12
Project: JavaAyo   File: SecureChatServerInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatServerHandler());
}
 
Example 13
Project: JavaAyo   File: SecureChatClientInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatClientHandler());
}
 
Example 14
Project: JavaAyo   File: RxtxClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 15
Project: baseio   File: MyNettyServer.java   View source code 6 votes vote down vote up
public static void service() throws Exception {
    ServerBootstrap bootstrap = new ServerBootstrap();
    bootstrap.group(bossGroup, workerGroup);
    bootstrap.channel(NioServerSocketChannel.class);
    bootstrap.childHandler(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
            pipeline.addLast(new LengthFieldPrepender(4));
            pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
            pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
            pipeline.addLast(new TcpServerHandler());
        }

    });
    ChannelFuture f = bootstrap.bind(IP, PORT).sync();
    f.channel().closeFuture().sync();
    System.out.println("TCP服务器已启动");
}
 
Example 16
Project: RHSocketServerDemo-Netty   File: TcpClient.java   View source code 6 votes vote down vote up
/**
 * 初始化Bootstrap
 * @return
 */
public static final Bootstrap getBootstrap(){
	EventLoopGroup group = new NioEventLoopGroup();
	Bootstrap b = new Bootstrap();
	b.group(group).channel(NioSocketChannel.class);
	b.handler(new ChannelInitializer<Channel>() {
		@Override
		protected void initChannel(Channel 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 TcpClientHandler());
		}
	});
	b.option(ChannelOption.SO_KEEPALIVE, true);
	return b;
}
 
Example 17
Project: RHSocketServerDemo-Netty   File: TcpServer.java   View source code 6 votes vote down vote up
protected static void run() throws Exception {
	ServerBootstrap b = new ServerBootstrap();
	b.group(bossGroup, workerGroup);
	b.channel(NioServerSocketChannel.class);
	b.childHandler(new ChannelInitializer<SocketChannel>() {
		@Override
		public 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(new TcpServerHandler());
		}
	});

	b.bind(IP, PORT).sync();
	System.out.println("TCP服务器已启动");
}
 
Example 18
Project: Camel   File: NettyHttpGetWithInvalidMessageTest.java   View source code 6 votes vote down vote up
@Override
protected JndiRegistry createRegistry() throws Exception {
    JndiRegistry registry = super.createRegistry();
    
    // setup the String encoder and decoder 
   
    StringDecoder stringDecoder = new StringDecoder();
    registry.bind("string-decoder", stringDecoder);

    StringEncoder stringEncoder = new StringEncoder();
    registry.bind("string-encoder", stringEncoder);

    List<ChannelHandler> decoders = new ArrayList<ChannelHandler>();
    decoders.add(stringDecoder);

    List<ChannelHandler> encoders = new ArrayList<ChannelHandler>();
    encoders.add(stringEncoder);

    registry.bind("encoders", encoders);
    registry.bind("decoders", decoders);
    
    return registry;
}
 
Example 19
Project: netty-cookbook   File: Receiver.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(new StringEncoder());
			p.addLast(new StringDecoder());
			p.addLast(new ChannelInboundHandlerAdapter() {
				@Override
				public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
					System.out.println(msg);
					ctx.close();
				}
			});
		}
	};
	BootstrapTemplate.newServerBootstrap(HOST, PORT, initializer);
}
 
Example 20
Project: netty-cookbook   File: Receiver.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
	ChannelInitializer<SocketChannel> initializer = new ChannelInitializer<SocketChannel>() {
		@Override
		public void initChannel(SocketChannel ch) throws Exception {
			ChannelPipeline p = ch.pipeline();
			p.addLast(new StringEncoder());
			p.addLast(new StringDecoder());
			p.addLast(new ChannelInboundHandlerAdapter() {
				@Override
				public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
					System.out.println(msg);
					ctx.close();
				}
			});
		}
	};
	BootstrapTemplate.newServerBootstrap(HOST, PORT, initializer);
}
 
Example 21
Project: netty4.0.27Learn   File: SecureChatServerInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatServerHandler());
}
 
Example 22
Project: netty4.0.27Learn   File: SecureChatClientInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new SecureChatClientHandler());
}
 
Example 23
Project: netty4.0.27Learn   File: RxtxClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 24
Project: netty-storm   File: NettySpoutServerInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc()));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8*8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new NettySpoutServerHandler(spout));
}
 
Example 25
Project: netty-storm   File: NettyConnectionInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.
    pipeline.addLast(sslCtx.newHandler(ch.alloc(), host, port));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast(new StringDecoder());
    pipeline.addLast(new StringEncoder());

    // and then business logic.
    pipeline.addLast(new NettyConnectionHandler());
}
 
Example 26
Project: ircd4j   File: IRCChannelInitializer.java   View source code 6 votes vote down vote up
@Override
protected void initChannel(SocketChannel ch) throws Exception {
    LineBasedFrameDecoder lineDecoder = new LineBasedFrameDecoder(MAX_LINE_LENGTH);
    StringDecoder stringDecoder = new StringDecoder(CHARSET); //FIXME: Should only split on CRLF, not on LF alone
    MessageDecoder messageDecoder = new MessageDecoder();
    MessageHandler messageHandler = new MessageHandler(handler);

    StringEncoder stringEncoder = new StringEncoder(CHARSET);
    MessageEncoder messageEncoder = new MessageEncoder();

    IdleStateHandler idleHandler = new IdleStateHandler(IDLE_TIMEOUT, 0, 0);

    // Inbound goes from first to last, outbound goes from last to first.
    // i.e. the outside is on the left/top, the inside is on the right/bottom
    ch.pipeline().addLast(lineDecoder).addLast(stringDecoder).addLast(messageDecoder).addLast(idleHandler).addLast(messageHandler)
            .addLast(stringEncoder).addLast(messageEncoder);

}
 
Example 27
Project: OpenHabbo   File: ServiceCommunicationManager.java   View source code 6 votes vote down vote up
private Bootstrap configureBootstrap(Bootstrap bootstrap) {
    bootstrap.group(this.loopGroup);
    bootstrap.channel(NioSocketChannel.class);

    bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
    bootstrap.option(ChannelOption.TCP_NODELAY, true);

    final ServiceCommunicationHandler handler = new ServiceCommunicationHandler();
    bootstrap.handler(new ChannelInitializer<SocketChannel>() {
        @Override
        protected void initChannel(SocketChannel socketChannel) throws Exception {
            socketChannel.pipeline().addLast(new StringEncoder());
            socketChannel.pipeline().addLast(new StringDecoder());
            socketChannel.pipeline().addLast(handler);
        }
    });

    bootstrap.remoteAddress(this.host, this.port);

    ChannelFuture future = bootstrap.connect();

    future.addListener(new ConnectionListener());
    this.channel = future.channel();
    return bootstrap;
}
 
Example 28
Project: netty-ssl-example   File: SecureSocketClientInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.

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

    pipeline.addLast("ssl", new SslHandler(engine));
    // On top of the SSL handler, add the text line codec.
    // pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
    pipeline.addLast("length-decoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4));
    pipeline.addLast("String-decoder", new StringDecoder());  
    pipeline.addLast("length-encoder", new LengthFieldPrepender(4));
    pipeline.addLast("String-encoder", new StringEncoder()); 
    pipeline.addLast("handler", new SecureSocketClientHandler());
}
 
Example 29
Project: javase-study   File: RxtxClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(RxtxChannel.class)
                .handler(new ChannelInitializer<RxtxChannel>() {
                    @Override
                    public void initChannel(RxtxChannel ch) throws Exception {
                        ch.pipeline().addLast(
                                new LineBasedFrameDecoder(32768),
                                new StringEncoder(),
                                new StringDecoder(),
                                new RxtxClientHandler()
                        );
                    }
                });

        ChannelFuture f = b.connect(new RxtxDeviceAddress(PORT)).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}
 
Example 30
Project: javase-study   File: FixedLengthChient.java   View source code 6 votes vote down vote up
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(host, port)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new FixedLengthFrameDecoder(1))
                                    .addLast(new StringDecoder())
                                    .addLast(new FixedLengthClientHandler());
                        }
                    });

            ChannelFuture cf = bootstrap.connect().sync();
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 31
Project: javase-study   File: LengthFieldChient.java   View source code 6 votes vote down vote up
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(host, port)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(100, 0, 4, 0, 4))
                                    .addLast(new StringDecoder())
                                    .addLast(new LengthFieldClientHandler());
                        }
                    });

            ChannelFuture cf = bootstrap.connect().sync();
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 32
Project: javase-study   File: ReadTimeOutChient.java   View source code 6 votes vote down vote up
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(host, port)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder())
                                    .addLast(new ReadTimeoutHandler());
                        }
                    });

            ChannelFuture cf = bootstrap.connect().sync();
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 33
Project: javase-study   File: IdleChient.java   View source code 6 votes vote down vote up
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(host, port)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder())
                                    .addLast(new IdleClientHandler());
                        }
                    });

            ChannelFuture cf = bootstrap.connect().sync();
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 34
Project: javase-study   File: FileClient.java   View source code 6 votes vote down vote up
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringEncoder())
//                                    .addLast(new LineBasedFrameDecoder(8192))
                                    .addLast(new StringDecoder())
                                    .addLast(new FileClientHandler());
                        }
                    });

            ChannelFuture cf = bootstrap.connect(host, port).sync();
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 35
Project: javase-study   File: ObjectEchoServer.java   View source code 6 votes vote down vote up
private void run(int port) throws InterruptedException, IOException {
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();

    try {
        ServerBootstrap bootstrap = new ServerBootstrap();
        bootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.INFO))
                                .addLast(new LengthFieldBasedFrameDecoder(200, 0, 4, 0, 4))
                                .addLast(new StringDecoder())
                                .addLast(new JsonStringToObjectDecoder())
                                .addLast(new ObjectEchoServerHandler());
                    }
                });
        bootstrap.bind(port).sync().channel().closeFuture().sync();
    } finally {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

}
 
Example 36
Project: javase-study   File: DelimitedChient.java   View source code 6 votes vote down vote up
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(host, port)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(20, Delimiters.lineDelimiter()))
                                    .addLast(new StringDecoder())
                                    .addLast(new DelimitedClientHandler());
                        }
                    });

            ChannelFuture cf = bootstrap.connect().sync();
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 37
Project: javase-study   File: DelimitedChient.java   View source code 6 votes vote down vote up
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(host, port)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new LineBasedFrameDecoder(20))
                                    .addLast(new StringDecoder())
                                    .addLast(new DelimitedClientHandler());
                        }
                    });

            ChannelFuture cf = bootstrap.connect().sync();
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 38
Project: javase-study   File: DelimitedChient.java   View source code 6 votes vote down vote up
public void run(String host, int port) throws Exception {

        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .remoteAddress(host, port)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new DelimiterBasedFrameDecoder(10, Unpooled.copiedBuffer(" ", CharsetUtil.UTF_8)))
                                    .addLast(new StringDecoder())
                                    .addLast(new DelimitedClientHandler());
                        }
                    });

            ChannelFuture cf = bootstrap.connect().sync();
            cf.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
 
Example 39
Project: netty4study   File: SecureChatClientInitializer.java   View source code 6 votes vote down vote up
@Override
public void initChannel(SocketChannel ch) throws Exception {
    ChannelPipeline pipeline = ch.pipeline();

    // Add SSL handler first to encrypt and decrypt everything.
    // In this example, we use a bogus certificate in the server side
    // and accept any invalid certificates in the client side.
    // You will need something more complicated to identify both
    // and server in the real world.

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

    pipeline.addLast("ssl", new SslHandler(engine));

    // On top of the SSL handler, add the text line codec.
    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(
            8192, Delimiters.lineDelimiter()));
    pipeline.addLast("decoder", new StringDecoder());
    pipeline.addLast("encoder", new StringEncoder());

    // and then business logic.
    pipeline.addLast("handler", new SecureChatClientHandler());
}
 
Example 40
Project: netty4study   File: RxtxClient.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    EventLoopGroup group = new OioEventLoopGroup();
    try {
        Bootstrap b = new Bootstrap();
        b.group(group)
         .channel(RxtxChannel.class)
         .handler(new ChannelInitializer<RxtxChannel>() {
             @Override
             public void initChannel(RxtxChannel ch) throws Exception {
                 ch.pipeline().addLast(
                     new LineBasedFrameDecoder(32768),
                     new StringEncoder(),
                     new StringDecoder(),
                     new RxtxClientHandler()
                 );
             }
         });

        ChannelFuture f = b.connect(new RxtxDeviceAddress("/dev/ttyUSB0")).sync();

        f.channel().closeFuture().sync();
    } finally {
        group.shutdownGracefully();
    }
}