io.netty.handler.codec.string.StringDecoder Java Examples
The following examples show how to use
io.netty.handler.codec.string.StringDecoder.
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: SecureChatServerInitializer.java From netty-4.1.22 with Apache License 2.0 | 7 votes |
@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 #2
Source File: NettyClient.java From netty-learning with Apache License 2.0 | 7 votes |
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 #3
Source File: NodeServerBootstrap.java From GoPush with GNU General Public License v2.0 | 6 votes |
@PostConstruct public void start() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workGroup) .channelFactory(NioServerSocketChannel::new) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { ChannelPipeline pipeline = socketChannel.pipeline(); pipeline.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)); pipeline.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8)); pipeline.addLast("frameEncoder", new LengthFieldPrepender(4)); pipeline.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8)); pipeline.addLast("idleStateHandler", new IdleStateHandler(300, 0, 0)); pipeline.addLast("handler", nodeChannelInBoundHandler); } }) .option(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_REUSEADDR, true) .option(ChannelOption.SO_SNDBUF, 2048) .option(ChannelOption.SO_RCVBUF, 1024); bootstrap.bind(goPushNodeServerConfig.getNodePort()).sync(); log.info("Node server start successful! listening port: {}", goPushNodeServerConfig.getNodePort()); }
Example #4
Source File: NettyClientDemo5.java From java-study with Apache License 2.0 | 6 votes |
/** * Netty创建全部都是实现自AbstractBootstrap。 * 客户端的是Bootstrap,服务端的则是ServerBootstrap。 **/ public static void main(String[] args) throws InterruptedException, IOException { 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(); //入参说明: 读超时时间、写超时时间、所有类型的超时时间、时间格式 //因为服务端设置的超时时间是5秒,所以设置4秒 p.addLast( new IdleStateHandler(0, 4, 0, TimeUnit.SECONDS)); p.addLast( new StringDecoder()); p.addLast( new StringEncoder()); p.addLast(new NettyClientHandlerDemo5()); //绑定自定义业务 } }); // 连接服务端 ch = b.connect(host, port).sync().channel(); System.out.println("客户端成功启动..."); //发送消息 // star(); }
Example #5
Source File: NettyClientDemo2.java From java-study with Apache License 2.0 | 6 votes |
/** * Netty创建全部都是实现自AbstractBootstrap。 * 客户端的是Bootstrap,服务端的则是ServerBootstrap。 **/ public static void main(String[] args) throws InterruptedException, IOException { 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 StringDecoder()); //绑定解码器 p.addLast(new NettyClientHandlerDemo2()); //绑定自定义业务 } }); // 连接服务端 ch = b.connect(host, port).sync().channel(); System.out.println("客户端成功启动..."); // star(); }
Example #6
Source File: SecureChatClientInitializer.java From x-pipe with Apache License 2.0 | 6 votes |
@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(createSslHandler(getClientSSLContext())); // 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 #7
Source File: NettyClientDemo4.java From java-study with Apache License 2.0 | 6 votes |
/** * Netty创建全部都是实现自AbstractBootstrap。 * 客户端的是Bootstrap,服务端的则是ServerBootstrap。 **/ public static void main(String[] args) throws InterruptedException, IOException { 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 StringDecoder()); //绑定自定义编码器 p.addLast(new NettyClientHandlerDemo4()); //绑定自定义业务 } }); // 连接服务端 ch = b.connect(host, port).sync().channel(); System.out.println("客户端成功启动..."); //发送消息 star(); }
Example #8
Source File: SecureChatClientInitializer.java From julongchain with Apache License 2.0 | 6 votes |
@Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // 添加SSL用于加密每一个步骤. // 在本次演示中我们在服务端使用了一张虚拟的证书,可以接收任何有效的客户端证书. // 但在真实场景中你需要一个更复杂的客户端和服务端标记. pipeline.addLast(sslCtx.newHandler(ch.alloc(), SecureChatClient.HOST, SecureChatClient.PORT)); // SSL之上添加编解码处理. pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); // 处理业务逻辑. pipeline.addLast(new SecureChatClientHandler()); }
Example #9
Source File: SecureChatServerInitializer.java From julongchain with Apache License 2.0 | 6 votes |
@Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // 添加SSL用于加密每一个步骤. // 在本次演示中我们在服务端使用了一张虚拟的证书,可以接收任何有效的客户端证书. // 但在真实场景中你需要一个更复杂的客户端和服务端标记. pipeline.addLast(sslCtx.newHandler(ch.alloc())); // SSL之上添加编解码处理. pipeline.addLast(new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); // 处理业务逻辑. pipeline.addLast(new SecureChatServerHandler()); }
Example #10
Source File: MonitorServer.java From Jupiter with Apache License 2.0 | 6 votes |
@Override public ChannelFuture bind(SocketAddress localAddress) { ServerBootstrap boot = bootstrap(); initChannelFactory(); boot.childHandler(new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) throws Exception { ch.pipeline().addLast( new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()), new StringDecoder(StandardCharsets.UTF_8), encoder, handler); } }); setOptions(); return boot.bind(localAddress); }
Example #11
Source File: Receiver.java From netty-cookbook with Apache License 2.0 | 6 votes |
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 #12
Source File: RxtxClient.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
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 #13
Source File: Receiver.java From netty-cookbook with Apache License 2.0 | 6 votes |
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 #14
Source File: EmbeddedRedisInitializer.java From dyno with Apache License 2.0 | 6 votes |
@Override protected void initChannel(final SocketChannel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); if (useSsl) { final SSLEngine sslEngine = sslContext.createSSLEngine(); sslEngine.setUseClientMode(false); sslEngine.getNeedClientAuth(); pipeline.addLast("sslHandler", new SslHandler(sslEngine)); } pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(new MockedResponseHandler(response)); }
Example #15
Source File: Server.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws InterruptedException { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workGroup = new NioEventLoopGroup(); ServerBootstrap serverBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup,workGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG,100) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringEncoder()); pipeline.addLast(new StringDecoder()); pipeline.addLast(new ServerHandler()); } }); ChannelFuture channelFuture = serverBootstrap.bind(new InetSocketAddress("172.28.86.151",8080)).sync(); channelFuture.channel().closeFuture().sync(); bossGroup.shutdownGracefully(); workGroup.shutdownGracefully(); }
Example #16
Source File: GraphiteClientPool.java From gruffalo with Apache License 2.0 | 5 votes |
public GraphiteClientPool(final EventLoopGroup eventLoopGroup, final StringDecoder decoder, final StringEncoder encoder, final Throttler throttler, final int inFlightBatchesHighThreshold, final MetricFactory metricFactory, final String graphiteRelayHosts) { Preconditions.checkNotNull(graphiteRelayHosts); Preconditions.checkNotNull(decoder, "decoder must not be null"); Preconditions.checkNotNull(encoder, "encoder must not be null"); Preconditions.checkNotNull(eventLoopGroup, "eventLoopGroup must not be null"); logger.info("Creating a client pool for [{}]", graphiteRelayHosts); final String[] hosts = graphiteRelayHosts.trim().split(","); pool = new GraphiteClient[hosts.length]; initClients(hosts, eventLoopGroup, decoder, encoder, throttler, inFlightBatchesHighThreshold, metricFactory); }
Example #17
Source File: RemoterNNHA.java From jumbune with GNU Lesser General Public License v3.0 | 5 votes |
/** * Fire and forget command. * Example usage: CommandWritable commandWritable = new CommandWritable(); * commandWritable.setCommandString("Sending Command"); * remoter.fireAndForgetCommand(commandWritable); * * @param commandWritable the command writable */ public void fireAndForgetCommand(CommandWritable commandWritable) { updateLeaderAgentInfo(); apisRetryCount++; ChannelFuture channelFuture; CyclicBarrier barrier = new CyclicBarrier(2); List<ChannelHandler> handlers = new LinkedList<ChannelHandler>(); handlers.add(new ObjectEncoder()); StringResponseHandler stringResponseHandler = new StringResponseHandler(); handlers.add(new StringDecoder()); handlers.add(stringResponseHandler); NNStateListener nnListener = new NNStateListener(this.clusterName, barrier, zkHosts); new Thread(nnListener).start(); try { // sending barrier as channel attachment for dynamic integration of // barrier channelFuture = acquireChannelFuture(handlers); writeToChannel(channelFuture.channel(), new String[] { "C", "M", "D" }, commandWritable, barrier); confirmBarrierAndGo(barrier); addCloseListener(channelFuture); channelFuture.channel().close(); } catch (Exception e) { if((nnListener.isNNFailed() || isNNChanged()) && apisRetryCount <= numApisRetries) { logger.warn("Namenode down !! retrying connection to active Namenode"); logger.warn("Initiating agent failover..."); electLeaderOnNN(); updateLeaderAgentInfo(); fireAndForgetCommand(commandWritable); updateGlobalState(); } else { logger.error("Error in fireAndForget Command - ", e); } }finally { nnListener.stop(); apisRetryCount = 0; } }
Example #18
Source File: UDTClientServerConnectionTest.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
@Override public void run() { final Bootstrap boot = new Bootstrap(); final ThreadFactory clientFactory = new DefaultThreadFactory("client"); final NioEventLoopGroup connectGroup = new NioEventLoopGroup(1, clientFactory, NioUdtProvider.BYTE_PROVIDER); try { boot.group(connectGroup) .channelFactory(NioUdtProvider.BYTE_CONNECTOR) .handler(new ChannelInitializer<UdtChannel>() { @Override protected void initChannel(final UdtChannel ch) throws Exception { final ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new StringDecoder( CharsetUtil.UTF_8)); pipeline.addLast("encoder", new StringEncoder( CharsetUtil.UTF_8)); pipeline.addLast("handler", new ClientHandler()); } }); channel = boot.connect(host, port).sync().channel(); isRunning = true; log.info("Client ready."); waitForRunning(false); log.info("Client closing..."); channel.close().sync(); isShutdown = true; log.info("Client is done."); } catch (final Throwable e) { log.error("Client failed.", e); } finally { connectGroup.shutdownGracefully().syncUninterruptibly(); } }
Example #19
Source File: Server.java From ARCHIVE-wildfly-swarm with Apache License 2.0 | 5 votes |
private void setupPipeline(final ChannelPipeline pipeline) { pipeline.addLast(NAME_CHANNEL_HANDLER_FRAME_DECODER, new DelimiterBasedFrameDecoder(2000, Delimiters.lineDelimiter())); pipeline.addLast(NAME_CHANNEL_HANDLER_STRING_DECODER, new StringDecoder(WireProtocol.CHARSET)); pipeline.addLast(NAME_CHANNEL_HANDLER_COMMAND, new StringCommandHandler()); }
Example #20
Source File: DefaultTl1Controller.java From onos with Apache License 2.0 | 5 votes |
@Override public void connectDevice(DeviceId deviceId) { Tl1Device device = deviceMap.get(deviceId); if (device == null || device.isConnected()) { return; } Bootstrap b = new Bootstrap(); b.group(workerGroup) .channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel socketChannel) throws Exception { socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(8192, DELIMITER)); socketChannel.pipeline().addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8)); // TODO //socketChannel.pipeline().addLast(new Tl1Decoder()); socketChannel.pipeline().addLast(new Tl1InboundHandler()); } }) .remoteAddress(device.ip().toInetAddress(), device.port()) .connect() .addListener((ChannelFuture channelFuture) -> { if (channelFuture.isSuccess()) { msgMap.put(channelFuture.channel(), new ConcurrentHashMap<>()); device.connect(channelFuture.channel()); tl1Listeners.forEach(l -> executor.execute(() -> l.deviceConnected(deviceId))); } }); }
Example #21
Source File: CodecSample.java From reactive-ipc-jvm with Apache License 2.0 | 5 votes |
private static void runLineBasedFrameDecoder() { TcpServer<String, String> transport = Netty4TcpServer.<String, String>create( 0, new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel channel) throws Exception { int bufferSize = 1; ChannelConfig config = channel.config(); config.setOption(ChannelOption.SO_RCVBUF, bufferSize); config.setOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(bufferSize)); channel.pipeline().addFirst( new LineBasedFrameDecoder(256), new StringDecoder(CharsetUtil.UTF_8), new StringEncoder(CharsetUtil.UTF_8)); } }); ReactorTcpServer.create(transport).start(connection -> { connection.log("input") .observeComplete(v -> LOG.info("Connection input complete")) .capacity(1) .consume(line -> { String response = "Hello " + line + "\n"; Streams.wrap(connection.writeWith(Streams.just(response))).consume(); }); return Streams.never(); }); }
Example #22
Source File: GraphiteMetricsPublisherTest.java From gruffalo with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws InterruptedException { final MetricFactory metricFactoryMock = Mockito.mock(MetricFactory.class); final Counter counterMock = Mockito.mock(Counter.class); Mockito.when(metricFactoryMock.createCounter(Mockito.anyString(), Mockito.anyString())).thenReturn(counterMock); NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(2); final Throttler throttler = Mockito.mock(Throttler.class); NettyGraphiteClient client = new NettyGraphiteClient(throttler, 1000, metricFactoryMock, "localhost:666"); String host = "localhost"; int port = 3003; GraphiteClientChannelInitializer channelInitializer = new GraphiteClientChannelInitializer(host, port, eventLoopGroup, new StringDecoder(), new StringEncoder(), new GraphiteChannelInboundHandler(client, host + ":" + port, throttler)); client.setChannelInitializer(channelInitializer); client.connect(); // Thread.sleep(20000); System.out.println("Begin bombardment..."); StopWatch time = new StopWatch(); time.start(); for (int i = 0; i < 10000000; i++) { client.publishMetrics(i + " - 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789\n"); if(i % 10000 == 0) { Thread.sleep(100); } if (i % 100000 == 0) { System.out.println(i); Thread.sleep(300); } } time.stop(); System.out.println("sent all data: " + time +"; shutting down..."); Thread.sleep(1000000); eventLoopGroup.shutdownGracefully(10, 20, TimeUnit.SECONDS); }
Example #23
Source File: CarbonLineServer.java From ffwd with Apache License 2.0 | 5 votes |
@Override public ChannelInitializer<Channel> initializer() { return new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) throws Exception { ch.pipeline().addLast(new LineBasedFrameDecoder(MAX_LINE)); ch.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8)); ch.pipeline().addLast(decoder, handler); } }; }
Example #24
Source File: HelloServer.java From netty-learning with Apache License 2.0 | 5 votes |
public void run() throws Exception { 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 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 HelloServerHandler()); } }); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); // (7) logger.info("server bind port:{}", port); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #25
Source File: DelimiterClient.java From netty-learning with Apache License 2.0 | 5 votes |
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 { ChannelPipeline p = ch.pipeline(); p.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(Constants.DELIMITER.getBytes()))); p.addLast(new StringDecoder()); p.addLast(new StringEncoder()); p.addLast(new DelimiterClientHandler()); } }); ChannelFuture future = b.connect(Constants.HOST, Constants.PORT).sync(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }
Example #26
Source File: WhirlpoolServer.java From whirlpool with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast("encoder", new HttpResponseEncoder()); p.addLast("decoder", new HttpRequestDecoder()); p.addLast("stringDecoder", new StringDecoder(CharsetUtil.UTF_8)); p.addLast("stringEncoder", new StringEncoder(CharsetUtil.UTF_8)); p.addLast("aggregator", new HttpObjectAggregator(65536)); p.addLast("handler", new WhirlpoolServerHandler()); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); logger.info("Whirlpool Server started"); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { logger.info("Whirlpool Server shutdown started"); // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); logger.info("Whirlpool Server shutdown completed"); } }
Example #27
Source File: Server.java From thorntail with Apache License 2.0 | 5 votes |
private void setupPipeline(final ChannelPipeline pipeline) { pipeline.addLast(NAME_CHANNEL_HANDLER_FRAME_DECODER, new DelimiterBasedFrameDecoder(2000, Delimiters.lineDelimiter())); pipeline.addLast(NAME_CHANNEL_HANDLER_STRING_DECODER, new StringDecoder(WireProtocol.CHARSET)); pipeline.addLast(NAME_CHANNEL_HANDLER_COMMAND, new StringCommandHandler()); }
Example #28
Source File: LineBasedServer.java From netty-learning with Apache License 2.0 | 5 votes |
public void bind(int port) throws Exception { 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 ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new LineBasedFrameDecoder(1024)); p.addLast(new StringDecoder()); p.addLast(new StringEncoder()); p.addLast(new LineServerHandler()); } }); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); // (7) logger.info("server bind port:{}", port); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #29
Source File: DelimiterServer.java From netty-learning with Apache License 2.0 | 5 votes |
public void bind(int port) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 1024) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new DelimiterBasedFrameDecoder(1024, Unpooled.copiedBuffer(Constants.DELIMITER.getBytes()))); p.addLast(new StringDecoder()); p.addLast(new StringEncoder()); p.addLast(new DelimiterServerHandler()); } }); // Bind and start to accept incoming connections. ChannelFuture f = b.bind(port).sync(); // (7) logger.info("server bind port:{}", port); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #30
Source File: LineBasedClient.java From netty-learning with Apache License 2.0 | 5 votes |
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 { ChannelPipeline p = ch.pipeline(); p.addLast(new LineBasedFrameDecoder(1024)); p.addLast(new StringDecoder()); p.addLast(new StringEncoder()); p.addLast(new LineClientHandler()); } }); ChannelFuture future = b.connect(Constants.HOST, Constants.PORT).sync(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } }