org.jboss.netty.channel.Channels Java Examples
The following examples show how to use
org.jboss.netty.channel.Channels.
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: ShuffleHandler.java From big-c with Apache License 2.0 | 6 votes |
@Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); if (sslFactory != null) { pipeline.addLast("ssl", new SslHandler(sslFactory.createSSLEngine())); } pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("aggregator", new HttpChunkAggregator(1 << 16)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("chunking", new ChunkedWriteHandler()); pipeline.addLast("shuffle", SHUFFLE); return pipeline; // TODO factor security manager into pipeline // TODO factor out encode/decode to permit binary shuffle // TODO factor out decode of index to permit alt. models }
Example #2
Source File: NettyClient.java From dubbox with Apache License 2.0 | 6 votes |
@Override protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); bootstrap = new ClientBootstrap(channelFactory); // config // @see org.jboss.netty.channel.socket.SocketChannelConfig bootstrap.setOption("keepAlive", true); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("connectTimeoutMillis", getTimeout()); final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", adapter.getDecoder()); pipeline.addLast("encoder", adapter.getEncoder()); pipeline.addLast("handler", nettyHandler); return pipeline; } }); }
Example #3
Source File: FileServerPipelineFactory.java From netty-file-parent with Apache License 2.0 | 6 votes |
public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); //它负责把字节解码成Http请求。 pipeline.addLast("decoder", new HttpRequestDecoder()); //当Server处理完消息后,需要向Client发送响应。那么需要把响应编码成字节,再发送出去。故添加HttpResponseEncoder处理器。 pipeline.addLast("encoder", new HttpResponseEncoder()); //它负责把多个HttpMessage组装成一个完整的Http请求或者响应。到底是组装成请求还是响应,则取决于它所处理的内容是请求的内容,还是响应的内容。 //这其实可以通过Inbound和Outbound来判断,对于Server端而言,在Inbound 端接收请求,在Outbound端返回响应。 //如果Server向Client返回的数据指定的传输编码是 chunked。则,Server不需要知道发送给Client的数据总长度是多少,它是通过分块发送的,参考分块传输编码 //pipeline.addLast("http-aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("deflater", new HttpContentCompressor()); //该通道处理器主要是为了处理大文件传输的情形。大文件传输时,需要复杂的状态管理,而ChunkedWriteHandler实现这个功能。 pipeline.addLast("http-chunked", new ChunkedWriteHandler()); //自定义的通道处理器,其目的是实现文件服务器的业务逻辑。 pipeline.addLast("handler", new FileServerHandler()); return pipeline; }
Example #4
Source File: ThriftFrameDecoder.java From ikasoa with MIT License | 6 votes |
protected ChannelBuffer tryDecodeFramedMessage(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, boolean stripFraming) { int messageStartReaderIndex = buffer.readerIndex(); int messageContentsOffset = stripFraming ? messageStartReaderIndex + MESSAGE_FRAME_SIZE : messageStartReaderIndex; int messageLength = buffer.getInt(messageStartReaderIndex) + MESSAGE_FRAME_SIZE; int messageContentsLength = messageStartReaderIndex + messageLength - messageContentsOffset; if (messageContentsLength > maxFrameSize) Channels.fireExceptionCaught(ctx, new TooLongFrameException(String.format("Maximum frame size of %d exceeded .", maxFrameSize))); if (messageLength == 0) { buffer.readerIndex(messageContentsOffset); return null; } else if (buffer.readableBytes() < messageLength) return null; else { ChannelBuffer messageBuffer = extractFrame(buffer, messageContentsOffset, messageContentsLength); buffer.readerIndex(messageStartReaderIndex + messageLength); return messageBuffer; } }
Example #5
Source File: NettyClient.java From anima with GNU General Public License v3.0 | 6 votes |
@Override public void doOpen() throws Throwable { bootstrap = new ClientBootstrap(channelFactory); bootstrap.setOption("keepAlive", true); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("connectTimeoutMillis", getConnectTimeout()); final NettyHandler nettyHandler = new NettyHandler(getConf(), this); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { NettyCodecAdapter adapter = new NettyCodecAdapter(getConf(),getCodec(), NettyClient.this); ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", adapter.getDecoder()); pipeline.addLast("encoder", adapter.getEncoder()); pipeline.addLast("handler", nettyHandler); return pipeline; } }); }
Example #6
Source File: RPCPipelineFactory.java From floodlight_with_topoguard with Apache License 2.0 | 6 votes |
@Override public ChannelPipeline getPipeline() throws Exception { RPCChannelHandler channelHandler = new RPCChannelHandler(syncManager, rpcService); IdleStateHandler idleHandler = new IdleStateHandler(timer, 5, 10, 0); ReadTimeoutHandler readTimeoutHandler = new ReadTimeoutHandler(timer, 30); ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("idle", idleHandler); pipeline.addLast("timeout", readTimeoutHandler); pipeline.addLast("handshaketimeout", new HandshakeTimeoutHandler(channelHandler, timer, 10)); pipeline.addLast("frameDecoder", new ThriftFrameDecoder(maxFrameSize)); pipeline.addLast("frameEncoder", new ThriftFrameEncoder()); pipeline.addLast("handler", channelHandler); return pipeline; }
Example #7
Source File: NettyDispatcher.java From ikasoa with MIT License | 6 votes |
private void writeResponseInOrder(ChannelHandlerContext ctx, TNettyMessage response, int responseSequenceId) { synchronized (responseMap) { int currentResponseId = lastResponseWrittenId.get() + 1; if (responseSequenceId != currentResponseId) responseMap.put(responseSequenceId, response); else { // 写入下一行的response. do { Channels.write(ctx.getChannel(), response); lastResponseWrittenId.incrementAndGet(); ++currentResponseId; response = responseMap.remove(currentResponseId); } while (null != response); if (DispatcherContext.isChannelReadBlocked(ctx) && dispatcherSequenceId.get() <= lastResponseWrittenId.get() + queuedResponseLimit) DispatcherContext.unblockChannelReads(ctx); } } }
Example #8
Source File: NettyClient.java From dubbox with Apache License 2.0 | 6 votes |
@Override protected void doOpen() throws Throwable { NettyHelper.setNettyLoggerFactory(); bootstrap = new ClientBootstrap(channelFactory); // config // @see org.jboss.netty.channel.socket.SocketChannelConfig bootstrap.setOption("keepAlive", true); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("connectTimeoutMillis", getTimeout()); final NettyHandler nettyHandler = new NettyHandler(getUrl(), this); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { NettyCodecAdapter adapter = new NettyCodecAdapter(getCodec(), getUrl(), NettyClient.this); ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("decoder", adapter.getDecoder()); pipeline.addLast("encoder", adapter.getEncoder()); pipeline.addLast("handler", nettyHandler); return pipeline; } }); }
Example #9
Source File: BootstrapPipelineFactory.java From floodlight_with_topoguard with Apache License 2.0 | 6 votes |
@Override public ChannelPipeline getPipeline() throws Exception { BootstrapChannelHandler handler = new BootstrapChannelHandler(bootstrap); ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("frameDecoder", new ThriftFrameDecoder(maxFrameSize)); pipeline.addLast("frameEncoder", new ThriftFrameEncoder()); pipeline.addLast("timeout", new BootstrapTimeoutHandler(timer, 10)); pipeline.addLast("handler", handler); return pipeline; }
Example #10
Source File: TestDelegationTokenRemoteFetcher.java From hadoop with Apache License 2.0 | 6 votes |
private ServerBootstrap startHttpServer(int port, final Token<DelegationTokenIdentifier> token, final URI url) { ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory(Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() throws Exception { return Channels.pipeline(new HttpRequestDecoder(), new HttpChunkAggregator(65536), new HttpResponseEncoder(), new CredentialsLogicHandler(token, url.toString())); } }); bootstrap.bind(new InetSocketAddress("localhost", port)); return bootstrap; }
Example #11
Source File: FrameDecoder.java From android-netty with Apache License 2.0 | 6 votes |
/** * Replace this {@link FrameDecoder} in the {@link ChannelPipeline} with the * given {@link ChannelHandler}. All remaining bytes in the * {@link ChannelBuffer} will get send to the new {@link ChannelHandler} * that was used as replacement * */ public void replace(String handlerName, ChannelHandler handler) { if (ctx == null) { throw new IllegalStateException("Replace cann only be called once the FrameDecoder is added to the ChannelPipeline"); } ChannelPipeline pipeline = ctx.getPipeline(); pipeline.addAfter(ctx.getName(), handlerName, handler); try { if (cumulation != null) { Channels.fireMessageReceived(ctx, cumulation.readBytes(actualReadableBytes())); } } finally { pipeline.remove(this); } }
Example #12
Source File: RemoteSyncPipelineFactory.java From floodlight_with_topoguard with Apache License 2.0 | 6 votes |
@Override public ChannelPipeline getPipeline() throws Exception { RemoteSyncChannelHandler channelHandler = new RemoteSyncChannelHandler(syncManager); ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("frameDecoder", new ThriftFrameDecoder(maxFrameSize)); pipeline.addLast("frameEncoder", new ThriftFrameEncoder()); pipeline.addLast("timeout", new RSHandshakeTimeoutHandler(channelHandler, timer, 3)); pipeline.addLast("handler", channelHandler); return pipeline; }
Example #13
Source File: BgpControllerImplTest.java From onos with Apache License 2.0 | 6 votes |
private Channel connectFrom(InetSocketAddress connectToSocket, SocketAddress localAddress) throws InterruptedException { ChannelFactory channelFactory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ChannelPipelineFactory pipelineFactory = () -> { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("BgpPeerFrameDecoderTest", peerFrameDecoder); pipeline.addLast("BgpPeerChannelHandlerTest", peerChannelHandler); return pipeline; }; peerBootstrap = new ClientBootstrap(channelFactory); peerBootstrap.setOption("child.keepAlive", true); peerBootstrap.setOption("child.tcpNoDelay", true); peerBootstrap.setPipelineFactory(pipelineFactory); Channel channel = peerBootstrap.connect(connectToSocket, localAddress).getChannel(); return channel; }
Example #14
Source File: BgpControllerImplTest.java From onos with Apache License 2.0 | 6 votes |
/** * Starts the BGP peer. * * @param connectToSocket the socket to connect to */ private void connect(InetSocketAddress connectToSocket) throws InterruptedException { ChannelFactory channelFactory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ChannelPipelineFactory pipelineFactory = () -> { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("BgpPeerFrameDecoderTest", peerFrameDecoder); pipeline.addLast("BgpPeerChannelHandlerTest", peerChannelHandler); return pipeline; }; peerBootstrap = new ClientBootstrap(channelFactory); peerBootstrap.setOption("child.keepAlive", true); peerBootstrap.setOption("child.tcpNoDelay", true); peerBootstrap.setPipelineFactory(pipelineFactory); peerBootstrap.connect(connectToSocket); }
Example #15
Source File: SimpleUdpServer.java From big-c with Apache License 2.0 | 6 votes |
public void run() { // Configure the client. DatagramChannelFactory f = new NioDatagramChannelFactory( Executors.newCachedThreadPool(), workerCount); server = new ConnectionlessBootstrap(f); server.setPipeline(Channels.pipeline(RpcUtil.STAGE_RPC_MESSAGE_PARSER, rpcProgram, RpcUtil.STAGE_RPC_UDP_RESPONSE)); server.setOption("broadcast", "false"); server.setOption("sendBufferSize", SEND_BUFFER_SIZE); server.setOption("receiveBufferSize", RECEIVE_BUFFER_SIZE); // Listen to the UDP port ch = server.bind(new InetSocketAddress(port)); InetSocketAddress socketAddr = (InetSocketAddress) ch.getLocalAddress(); boundPort = socketAddr.getPort(); LOG.info("Started listening to UDP requests at port " + boundPort + " for " + rpcProgram + " with workerCount " + workerCount); }
Example #16
Source File: MemcachedCommandHandler.java From fqueue with Apache License 2.0 | 5 votes |
protected void handleReplace(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) throws DatabaseException, Exception { Cache.StoreResponse ret; ret = cache.replace(command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel .getRemoteAddress()); }
Example #17
Source File: HandshakeTimeoutHandler.java From floodlight_with_topoguard with Apache License 2.0 | 5 votes |
@Override public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (!ctx.getChannel().isOpen()) { return; } if (!handler.isClientConnection && ((handler.remoteNode == null || !handler.rpcService.isConnected(handler.remoteNode. getNodeId())))) Channels.fireExceptionCaught(ctx, EXCEPTION); }
Example #18
Source File: MemcachedCommandHandler.java From fqueue with Apache License 2.0 | 5 votes |
protected void handleCas(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) throws DatabaseException, Exception { Cache.StoreResponse ret; ret = cache.cas(command.cas_key, command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel .getRemoteAddress()); }
Example #19
Source File: MemcachedCommandHandler.java From fqueue with Apache License 2.0 | 5 votes |
protected void handleAdd(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) throws DatabaseException, Exception { Cache.StoreResponse ret; ret = cache.add(command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel .getRemoteAddress()); }
Example #20
Source File: MemcachedCommandHandler.java From fqueue with Apache License 2.0 | 5 votes |
protected void handlePrepend(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) throws DatabaseException, Exception { Cache.StoreResponse ret; ret = cache.prepend(command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel .getRemoteAddress()); }
Example #21
Source File: MemcachedCommandHandler.java From fqueue with Apache License 2.0 | 5 votes |
protected void handleIncr(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) throws DatabaseException, Exception { Integer incrDecrResp = cache.get_add(command.keys.get(0), command.incrAmount); // TODO // support // default // value // and // expiry!! Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command) .withIncrDecrResponse(incrDecrResp), channel.getRemoteAddress()); }
Example #22
Source File: MemcachedCommandHandler.java From fqueue with Apache License 2.0 | 5 votes |
protected void handleStats(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, int cmdKeysSize, Channel channel) { String option = ""; if (cmdKeysSize > 0) { option = command.keys.get(0); } Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withStatResponse(cache.stat( option, channelHandlerContext)), channel.getRemoteAddress()); }
Example #23
Source File: MyChannelPipelineFactory.java From whiteboard with Apache License 2.0 | 5 votes |
@Override public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); // ��������� pipeline.addLast("objectencoder", new ObjectEncoder()); // ��������� pipeline.addLast("objectdecoder", new ObjectDecoder(ClassResolvers.cacheDisabled(this.getClass().getClassLoader()))); // ��������ҵ���� pipeline.addLast("clientHandler", myClientHandler); return pipeline; }
Example #24
Source File: MemcachedCommandHandler.java From fqueue with Apache License 2.0 | 5 votes |
protected void handleIncr(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) throws DatabaseException, Exception { Integer incrDecrResp = cache.get_add(command.keys.get(0), command.incrAmount); // TODO // support // default // value // and // expiry!! Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command) .withIncrDecrResponse(incrDecrResp), channel.getRemoteAddress()); }
Example #25
Source File: NettySend.java From jlogstash-input-plugin with Apache License 2.0 | 5 votes |
public void connect(){ bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setOption("tcpNoDelay", false); bootstrap.setOption("keepAlive", true); final NettyClientHandler handler = new NettyClientHandler(this, timer); bootstrap.setPipelineFactory(new ChannelPipelineFactory() { public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("handler", handler); pipeline.addLast("encoder", new StringEncoder()); return pipeline; } }); bootstrap.setOption("remoteAddress", new InetSocketAddress(host, port)); try { ChannelFuture future = bootstrap.connect().sync(); channel = future.getChannel(); } catch (Exception e) { logger.error(ExceptionUtil.getErrorMessage(e)); bootstrap.releaseExternalResources(); System.exit(-1);//第一次连接出现异常直接退出,不走重连 } }
Example #26
Source File: ClientCodecPipelineFactory.java From pinpoint with Apache License 2.0 | 5 votes |
@Override public ChannelPipeline newPipeline() { ChannelPipeline pipeline = Channels.pipeline(); pipeline.addLast("encoder", new PacketEncoder()); pipeline.addLast("decoder", new PacketDecoder()); return pipeline; }
Example #27
Source File: ThriftFrameDecoder.java From ikasoa with MIT License | 5 votes |
protected ChannelBuffer tryDecodeUnframedMessage(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, TProtocolFactory inputProtocolFactory) throws TException { int messageLength = 0; int messageStartReaderIndex = buffer.readerIndex(); try { TNettyTransport decodeAttemptTransport = new TNettyTransport(channel, buffer, TNettyTransportType.UNFRAMED); int initialReadBytes = decodeAttemptTransport.getReadByteCount(); TProtocol inputProtocol = inputProtocolFactory.getProtocol(decodeAttemptTransport); inputProtocol.readMessageBegin(); TProtocolUtil.skip(inputProtocol, TType.STRUCT); inputProtocol.readMessageEnd(); messageLength = decodeAttemptTransport.getReadByteCount() - initialReadBytes; } catch (TTransportException | IndexOutOfBoundsException e) { return null; } finally { if (buffer.readerIndex() - messageStartReaderIndex > maxFrameSize) Channels.fireExceptionCaught(ctx, new TooLongFrameException(String.format("Maximum frame size of %d exceeded .", maxFrameSize))); buffer.readerIndex(messageStartReaderIndex); } if (messageLength <= 0) return null; ChannelBuffer messageBuffer = extractFrame(buffer, messageStartReaderIndex, messageLength); buffer.readerIndex(messageStartReaderIndex + messageLength); return messageBuffer; }
Example #28
Source File: MemcachedCommandHandler.java From fqueue with Apache License 2.0 | 5 votes |
protected void handleCas(ChannelHandlerContext channelHandlerContext, CommandMessage<CACHE_ELEMENT> command, Channel channel) throws DatabaseException, Exception { Cache.StoreResponse ret; ret = cache.cas(command.cas_key, command.element); Channels.fireMessageReceived(channelHandlerContext, new ResponseMessage(command).withResponse(ret), channel .getRemoteAddress()); }
Example #29
Source File: SimpleTcpClient.java From big-c with Apache License 2.0 | 5 votes |
protected ChannelPipelineFactory setPipelineFactory() { this.pipelineFactory = new ChannelPipelineFactory() { @Override public ChannelPipeline getPipeline() { return Channels.pipeline( RpcUtil.constructRpcFrameDecoder(), new SimpleTcpClientHandler(request)); } }; return this.pipelineFactory; }
Example #30
Source File: NettyDispatcher.java From ikasoa with MIT License | 5 votes |
private void writeResponse(ChannelHandlerContext ctx, TNettyMessage response, int responseSequenceId, boolean isOrderedResponsesRequired) { if (isOrderedResponsesRequired) writeResponseInOrder(ctx, response, responseSequenceId); else { Channels.write(ctx.getChannel(), response); lastResponseWrittenId.incrementAndGet(); } }