List of usage examples for io.netty.handler.codec FixedLengthFrameDecoder FixedLengthFrameDecoder
public FixedLengthFrameDecoder(int frameLength)
From source file:book.netty.n5fixedLenC5P2.EchoServer.java
License:Apache License
public void bind(int port) throws Exception { // ??NIO//from w ww. j a va 2 s . co m EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new FixedLengthFrameDecoder(20)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new EchoServerHandler()); } }); // ??? ChannelFuture f = b.bind(port).sync(); // ??? f.channel().closeFuture().sync(); } finally { // ? bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:books.netty.frame.fixedLen.EchoServer.java
License:Apache License
public void bind(int port) throws Exception { // ??NIO/* w ww .j a v a2s. c om*/ EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ch.pipeline().addLast(new FixedLengthFrameDecoder(20)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new EchoServerHandler()); } }); // ??? ChannelFuture f = b.bind(port).sync(); // ??? f.channel().closeFuture().sync(); } finally { // ? bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.alltobid.quotabid.BidClientInitializer.java
License:Apache License
@Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline();/* w ww . j a v a 2 s . c om*/ p.addLast(BidClient.globalTrafficShapingHandler); p.addLast(new FixedLengthFrameDecoder(100)); p.addLast(stringDecoder); p.addLast(loggingHandler); p.addLast(BidClient.bidClientHandler); }
From source file:com.mobius.software.mqtt.parser.test.TestConnack.java
License:Open Source License
@Before public void setUp() { channel = new EmbeddedChannel(new FixedLengthFrameDecoder(10000)); alloc = channel.alloc();// w w w. jav a 2 s. c o m expected = new Connack(true, ConnackCode.ACCEPTED); }
From source file:com.mobius.software.mqtt.parser.test.TestConnect.java
License:Open Source License
@Before public void setUp() { channel = new EmbeddedChannel(new FixedLengthFrameDecoder(10000)); alloc = channel.alloc();/*from w ww .j a v a2 s . com*/ expected = new Connect("John", "1234567890", "_123456789", true, 60, new Will(new Topic(new Text("lookup"), QoS.AT_LEAST_ONCE), "John: i'll be back".getBytes(), true)); }
From source file:com.phei.netty.frame.fixedLen.EchoClient.java
License:Apache License
public void connect(int port, String host) throws Exception { // ?NIO// w w w .ja v a2 s . c o m EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new FixedLengthFrameDecoder(20)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new EchoClientHandler()); } }); // ?? ChannelFuture f = b.connect(host, port).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:com.phei.netty.frame.fixedLen.TimeClient.java
License:Apache License
public void connect(int port, String host) throws Exception { // ?NIO//from w w w.j a v a 2 s. c o m EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new FixedLengthFrameDecoder(20)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new TimeClientHandler()); } }); // ?? ChannelFuture f = b.connect(host, port).sync(); // f.channel().closeFuture().sync(); } finally { // NIO group.shutdownGracefully(); } }
From source file:org.apache.giraph.comm.netty.handler.SaslClientHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { WritableRequest decodedMessage = decode(ctx, msg); // Generate SASL response to server using Channel-local SASL client. SaslNettyClient saslNettyClient = ctx.attr(NettyClient.SASL).get(); if (saslNettyClient == null) { throw new Exception( "handleUpstream: saslNettyClient was unexpectedly " + "null for channel: " + ctx.channel()); }/* ww w. ja v a 2 s . c o m*/ if (decodedMessage.getClass() == SaslCompleteRequest.class) { if (LOG.isDebugEnabled()) { LOG.debug("handleUpstream: Server has sent us the SaslComplete " + "message. Allowing normal work to proceed."); } synchronized (saslNettyClient.getAuthenticated()) { saslNettyClient.getAuthenticated().notify(); } if (!saslNettyClient.isComplete()) { LOG.error("handleUpstream: Server returned a Sasl-complete message, " + "but as far as we can tell, we are not authenticated yet."); throw new Exception("handleUpstream: Server returned a " + "Sasl-complete message, but as far as " + "we can tell, we are not authenticated yet."); } // Remove SaslClientHandler and replace LengthFieldBasedFrameDecoder // from client pipeline. ctx.pipeline().remove(this); ctx.pipeline().replace("length-field-based-frame-decoder", "fixed-length-frame-decoder", new FixedLengthFrameDecoder(RequestServerHandler.RESPONSE_BYTES)); return; } SaslTokenMessageRequest serverToken = (SaslTokenMessageRequest) decodedMessage; if (LOG.isDebugEnabled()) { LOG.debug( "handleUpstream: Responding to server's token of length: " + serverToken.getSaslToken().length); } // Generate SASL response (but we only actually send the response if it's // non-null. byte[] responseToServer = saslNettyClient.saslResponse(serverToken); if (responseToServer == null) { // If we generate a null response, then authentication has completed (if // not, warn), and return without sending a response back to the server. if (LOG.isDebugEnabled()) { LOG.debug( "handleUpstream: Response to server is null: " + "authentication should now be complete."); } if (!saslNettyClient.isComplete()) { LOG.warn("handleUpstream: Generated a null response, " + "but authentication is not complete."); } return; } else { if (LOG.isDebugEnabled()) { LOG.debug("handleUpstream: Response to server token has length:" + responseToServer.length); } } // Construct a message containing the SASL response and send it to the // server. SaslTokenMessageRequest saslResponse = new SaslTokenMessageRequest(responseToServer); ctx.channel().writeAndFlush(saslResponse); }
From source file:org.apache.giraph.comm.netty.NettyClient.java
License:Apache License
/** * Only constructor// w w w . j a va 2 s .c o m * * @param context Context for progress * @param conf Configuration * @param myTaskInfo Current task info * @param exceptionHandler handler for uncaught exception. Will * terminate job. */ public NettyClient(Mapper<?, ?, ?, ?>.Context context, final ImmutableClassesGiraphConfiguration conf, TaskInfo myTaskInfo, final Thread.UncaughtExceptionHandler exceptionHandler) { this.context = context; this.myTaskInfo = myTaskInfo; this.channelsPerServer = GiraphConstants.CHANNELS_PER_SERVER.get(conf); sendBufferSize = CLIENT_SEND_BUFFER_SIZE.get(conf); receiveBufferSize = CLIENT_RECEIVE_BUFFER_SIZE.get(conf); limitNumberOfOpenRequests = conf.getBoolean(LIMIT_NUMBER_OF_OPEN_REQUESTS, LIMIT_NUMBER_OF_OPEN_REQUESTS_DEFAULT); if (limitNumberOfOpenRequests) { maxNumberOfOpenRequests = conf.getInt(MAX_NUMBER_OF_OPEN_REQUESTS, MAX_NUMBER_OF_OPEN_REQUESTS_DEFAULT); if (LOG.isInfoEnabled()) { LOG.info("NettyClient: Limit number of open requests to " + maxNumberOfOpenRequests); } } else { maxNumberOfOpenRequests = -1; } maxRequestMilliseconds = MAX_REQUEST_MILLISECONDS.get(conf); maxConnectionFailures = NETTY_MAX_CONNECTION_FAILURES.get(conf); waitingRequestMsecs = WAITING_REQUEST_MSECS.get(conf); maxPoolSize = GiraphConstants.NETTY_CLIENT_THREADS.get(conf); maxResolveAddressAttempts = MAX_RESOLVE_ADDRESS_ATTEMPTS.get(conf); clientRequestIdRequestInfoMap = new MapMaker().concurrencyLevel(maxPoolSize).makeMap(); handlerToUseExecutionGroup = NETTY_CLIENT_EXECUTION_AFTER_HANDLER.get(conf); useExecutionGroup = NETTY_CLIENT_USE_EXECUTION_HANDLER.get(conf); if (useExecutionGroup) { int executionThreads = NETTY_CLIENT_EXECUTION_THREADS.get(conf); executionGroup = new DefaultEventExecutorGroup(executionThreads, ThreadUtils.createThreadFactory("netty-client-exec-%d", exceptionHandler)); if (LOG.isInfoEnabled()) { LOG.info("NettyClient: Using execution handler with " + executionThreads + " threads after " + handlerToUseExecutionGroup + "."); } } else { executionGroup = null; } workerGroup = new NioEventLoopGroup(maxPoolSize, ThreadUtils.createThreadFactory("netty-client-worker-%d", exceptionHandler)); bootstrap = new Bootstrap(); bootstrap.group(workerGroup).channel(NioSocketChannel.class) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, MAX_CONNECTION_MILLISECONDS_DEFAULT) .option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true) .option(ChannelOption.SO_SNDBUF, sendBufferSize).option(ChannelOption.SO_RCVBUF, receiveBufferSize) .option(ChannelOption.ALLOCATOR, conf.getNettyAllocator()) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { /*if_not[HADOOP_NON_SECURE]*/ if (conf.authenticate()) { LOG.info("Using Netty with authentication."); // Our pipeline starts with just byteCounter, and then we use // addLast() to incrementally add pipeline elements, so that we // can name them for identification for removal or replacement // after client is authenticated by server. // After authentication is complete, the pipeline's SASL-specific // functionality is removed, restoring the pipeline to exactly the // same configuration as it would be without authentication. PipelineUtils.addLastWithExecutorCheck("clientInboundByteCounter", inboundByteCounter, handlerToUseExecutionGroup, executionGroup, ch); if (conf.doCompression()) { PipelineUtils.addLastWithExecutorCheck("compressionDecoder", conf.getNettyCompressionDecoder(), handlerToUseExecutionGroup, executionGroup, ch); } PipelineUtils.addLastWithExecutorCheck("clientOutboundByteCounter", outboundByteCounter, handlerToUseExecutionGroup, executionGroup, ch); if (conf.doCompression()) { PipelineUtils.addLastWithExecutorCheck("compressionEncoder", conf.getNettyCompressionEncoder(), handlerToUseExecutionGroup, executionGroup, ch); } // The following pipeline component is needed to decode the // server's SASL tokens. It is replaced with a // FixedLengthFrameDecoder (same as used with the // non-authenticated pipeline) after authentication // completes (as in non-auth pipeline below). PipelineUtils.addLastWithExecutorCheck("length-field-based-frame-decoder", new LengthFieldBasedFrameDecoder(1024, 0, 4, 0, 4), handlerToUseExecutionGroup, executionGroup, ch); PipelineUtils.addLastWithExecutorCheck("request-encoder", new RequestEncoder(conf), handlerToUseExecutionGroup, executionGroup, ch); // The following pipeline component responds to the server's SASL // tokens with its own responses. Both client and server share the // same Hadoop Job token, which is used to create the SASL // tokens to authenticate with each other. // After authentication finishes, this pipeline component // is removed. PipelineUtils.addLastWithExecutorCheck("sasl-client-handler", new SaslClientHandler(conf), handlerToUseExecutionGroup, executionGroup, ch); PipelineUtils.addLastWithExecutorCheck("response-handler", new ResponseClientHandler(clientRequestIdRequestInfoMap, conf), handlerToUseExecutionGroup, executionGroup, ch); } else { LOG.info("Using Netty without authentication."); /*end[HADOOP_NON_SECURE]*/ PipelineUtils.addLastWithExecutorCheck("clientInboundByteCounter", inboundByteCounter, handlerToUseExecutionGroup, executionGroup, ch); if (conf.doCompression()) { PipelineUtils.addLastWithExecutorCheck("compressionDecoder", conf.getNettyCompressionDecoder(), handlerToUseExecutionGroup, executionGroup, ch); } PipelineUtils.addLastWithExecutorCheck("clientOutboundByteCounter", outboundByteCounter, handlerToUseExecutionGroup, executionGroup, ch); if (conf.doCompression()) { PipelineUtils.addLastWithExecutorCheck("compressionEncoder", conf.getNettyCompressionEncoder(), handlerToUseExecutionGroup, executionGroup, ch); } PipelineUtils.addLastWithExecutorCheck("fixed-length-frame-decoder", new FixedLengthFrameDecoder(RequestServerHandler.RESPONSE_BYTES), handlerToUseExecutionGroup, executionGroup, ch); PipelineUtils.addLastWithExecutorCheck("request-encoder", new RequestEncoder(conf), handlerToUseExecutionGroup, executionGroup, ch); PipelineUtils.addLastWithExecutorCheck("response-handler", new ResponseClientHandler(clientRequestIdRequestInfoMap, conf), handlerToUseExecutionGroup, executionGroup, ch); /*if_not[HADOOP_NON_SECURE]*/ } /*end[HADOOP_NON_SECURE]*/ } }); }
From source file:org.traccar.protocol.FlexCommProtocol.java
License:Apache License
public FlexCommProtocol() { addServer(new TrackerServer(false, getName()) { @Override//from ww w .ja va2s . com protected void addProtocolHandlers(PipelineBuilder pipeline) { pipeline.addLast(new FixedLengthFrameDecoder(2 + 2 + 101 + 5)); pipeline.addLast(new StringEncoder()); pipeline.addLast(new StringDecoder()); pipeline.addLast(new FlexCommProtocolDecoder(FlexCommProtocol.this)); } }); }