io.netty.channel.Channel源码实例Demo

类io.netty.channel.Channel源码实例Demo

下面列出了io.netty.channel.Channel 类实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
protected void processResponseFrame(Channel channel, ModbusFrame respFrame) {
	super.processResponseFrame(channel, respFrame);
	int respTransactionIdentifier = respFrame.getHeader().getTransactionIdentifier();
	ModbusFrame reqFrame = ModebusFrameCacheFactory.getInstance().getRequestCache()
			.get(respTransactionIdentifier - this.getTransactionIdentifierOffset());
	boolean isErr = false;
	if (reqFrame != null) {
		if (reqFrame.getFunction() instanceof AbstractFunction) {
			AbstractFunction reqFunc = (AbstractFunction) reqFrame.getFunction();
			ModbusFunction respFunc = respFrame.getFunction();
			processResponseFrame(channel, reqFunc, respFunc);
		} else {
			isErr = true;
		}
	} else {
		isErr = true;
	}
	if (isErr) {
		logger.error(String.format("req is null:%s;%s", channel.remoteAddress(), respFrame));
	}
}
 
@Test
public void cancelExecuteFuture_channelAcquired_submitsRunnable() {
    EventLoop mockEventLoop = mock(EventLoop.class);
    Channel mockChannel = mock(Channel.class);
    when(mockChannel.eventLoop()).thenReturn(mockEventLoop);

    when(mockChannelPool.acquire(any(Promise.class))).thenAnswer((Answer<Promise>) invocationOnMock -> {
        Promise p = invocationOnMock.getArgumentAt(0, Promise.class);
        p.setSuccess(mockChannel);
        return p;
    });

    CompletableFuture<Void> executeFuture = nettyRequestExecutor.execute();

    executeFuture.cancel(true);

    verify(mockEventLoop).submit(any(Runnable.class));
}
 
public NioUdtMessageConnectorChannel(final Channel parent, final SocketChannelUDT channelUDT) {
    super(parent, channelUDT, OP_READ);
    try {
        channelUDT.configureBlocking(false);
        switch (channelUDT.socketUDT().status()) {
        case INIT:
        case OPENED:
            config = new DefaultUdtChannelConfig(this, channelUDT, true);
            break;
        default:
            config = new DefaultUdtChannelConfig(this, channelUDT, false);
            break;
        }
    } catch (final Exception e) {
        try {
            channelUDT.close();
        } catch (final Exception e2) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed to close channel.", e2);
            }
        }
        throw new ChannelException("Failed to configure channel.", e);
    }
}
 
public HashMap<String, HashMap<Channel, ClientChannelInfo>> getGroupChannelTable() {
    HashMap<String /* group name */, HashMap<Channel, ClientChannelInfo>> newGroupChannelTable =
            new HashMap<String, HashMap<Channel, ClientChannelInfo>>();
    try {
        if (this.groupChannelLock.tryLock(LockTimeoutMillis, TimeUnit.MILLISECONDS)){
            try {
                newGroupChannelTable.putAll(groupChannelTable);
            } finally {
                groupChannelLock.unlock();
            }
        }
    } catch (InterruptedException e) {
       log.error("",e);
    }
    return newGroupChannelTable;
}
 
源代码5 项目: serve   文件: ModelServerTest.java
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testRegisterModelHttpError"})
public void testRegisterModelInvalidPath() throws InterruptedException {
    Channel channel = TestUtils.connect(true, configManager);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=..%2Ffake.mar&synchronous=false");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.NOT_FOUND.code());
    Assert.assertEquals(resp.getMessage(), "Relative path is not allowed in url: ../fake.mar");
}
 
@Override
public void masterDisconntected(Channel channel) {
    super.masterDisconntected(channel);

    redisKeeperServer.getKeeperMonitor().getReplicationStoreStats().refreshReplDownSince(System.currentTimeMillis());
    long interval = System.currentTimeMillis() - connectedTime;
    long scheduleTime = masterConnectRetryDelaySeconds * 1000 - interval;
    if (scheduleTime < 0) {
        scheduleTime = 0;
    }
    logger.info("[masterDisconntected][reconnect after {} ms]", scheduleTime);
    scheduled.schedule(new AbstractExceptionLogTask() {

        @Override
        public void doRun() {
            connectWithMaster();
        }
    }, scheduleTime, TimeUnit.MILLISECONDS);
}
 
源代码7 项目: cxf   文件: NettyHttpServletHandler.java
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    LOG.log(Level.SEVERE, "UNEXPECTED_EXCEPCTION_IN_NETTY_SERVLET_HANDLER", cause);

    interceptOnRequestFailed(ctx, cause);

    Channel ch = ctx.channel();
    if (cause instanceof IllegalArgumentException) {

        ch.close();

    } else {

        if (cause instanceof TooLongFrameException) {
            sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            return;
        }

        if (ch.isActive()) {
            sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }

    }
    ctx.close();
}
 
源代码8 项目: incubator-hivemall   文件: MixClient.java
@Override
public void sendCancelRequest(@Nonnull Object feature, @Nonnull MixedWeight mixed)
        throws Exception {
    assert (initialized);

    float weight = mixed.getWeight();
    float covar = mixed.getCovar();
    int deltaUpdates = mixed.getDeltaUpdates();

    MixMessage msg = new MixMessage(event, feature, weight, covar, deltaUpdates, true);
    assert (groupID != null);
    msg.setGroupID(groupID);

    // TODO REVIEWME consider mix server faults (what if mix server dead? Do not send cancel request?)
    NodeInfo server = router.selectNode(msg);
    Channel ch = channelMap.get(server);
    if (!ch.isActive()) {// reconnect
        SocketAddress remoteAddr = server.getSocketAddress();
        ch.connect(remoteAddr).sync();
    }

    ch.writeAndFlush(msg); // send asynchronously in the background
}
 
源代码9 项目: Jupiter   文件: ConnectorHandler.java
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Channel ch = ctx.channel();

    if (msg instanceof JResponsePayload) {
        try {
            processor.handleResponse(NettyChannel.attachChannel(ch), (JResponsePayload) msg);
        } catch (Throwable t) {
            logger.error("An exception was caught: {}, on {} #channelRead().", StackTraceUtil.stackTrace(t), ch);
        }
    } else {
        logger.warn("Unexpected message type received: {}, channel: {}.", msg.getClass(), ch);

        ReferenceCountUtil.release(msg);
    }
}
 
源代码10 项目: grpc-java   文件: NettyChannelBuilder.java
NettyTransportFactory(ProtocolNegotiator protocolNegotiator,
    ChannelFactory<? extends Channel> channelFactory,
    Map<ChannelOption<?>, ?> channelOptions, ObjectPool<? extends EventLoopGroup> groupPool,
    boolean autoFlowControl, int flowControlWindow, int maxMessageSize, int maxHeaderListSize,
    long keepAliveTimeNanos, long keepAliveTimeoutNanos, boolean keepAliveWithoutCalls,
    TransportTracer.Factory transportTracerFactory, LocalSocketPicker localSocketPicker,
    boolean useGetForSafeMethods) {
  this.protocolNegotiator = checkNotNull(protocolNegotiator, "protocolNegotiator");
  this.channelFactory = channelFactory;
  this.channelOptions = new HashMap<ChannelOption<?>, Object>(channelOptions);
  this.groupPool = groupPool;
  this.group = groupPool.getObject();
  this.autoFlowControl = autoFlowControl;
  this.flowControlWindow = flowControlWindow;
  this.maxMessageSize = maxMessageSize;
  this.maxHeaderListSize = maxHeaderListSize;
  this.keepAliveTimeNanos = new AtomicBackoff("keepalive time nanos", keepAliveTimeNanos);
  this.keepAliveTimeoutNanos = keepAliveTimeoutNanos;
  this.keepAliveWithoutCalls = keepAliveWithoutCalls;
  this.transportTracerFactory = transportTracerFactory;
  this.localSocketPicker =
      localSocketPicker != null ? localSocketPicker : new LocalSocketPicker();
  this.useGetForSafeMethods = useGetForSafeMethods;
}
 
源代码11 项目: multi-model-server   文件: ModelServerTest.java
private void testLoadingMemoryError() throws InterruptedException {
    Channel channel = connect(true);
    Assert.assertNotNull(channel);
    result = null;
    latch = new CountDownLatch(1);
    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=loading-memory-error&model_name=memory_error&runtime=python&initial_workers=1&synchronous=true");
    channel.writeAndFlush(req);
    latch.await();

    Assert.assertEquals(httpStatus, HttpResponseStatus.INSUFFICIENT_STORAGE);
    channel.close();
}
 
源代码12 项目: reef   文件: AbstractNettyEventListener.java
@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
  final Channel channel = ctx.channel();
  final byte[] message = (byte[]) msg;

  if (LOG.isLoggable(Level.FINEST)) {
    LOG.log(Level.FINEST, "MessageEvent: local: {0} remote: {1} :: {2}", new Object[]{
        channel.localAddress(), channel.remoteAddress(), message});
  }

  if (message.length > 0) {
    // send to the dispatch stage
    this.stage.onNext(this.getTransportEvent(message, channel));
  }
}
 
源代码13 项目: JLilyPad   文件: ProxyOutboundHandler.java
@Override
protected void channelRead0(ChannelHandlerContext context, Packet packet) throws Exception {
	Channel channel = context.channel();
	if(this.proxySession == null || !this.proxySession.isInboundConnected()) {
		channel.close();
		return;
	}
	switch(this.state) {
	case LOGIN:
		if(packet.getOpcode() == LoginSuccessPacket.opcode) {
			this.state = ProxyState.INIT;
			this.proxySession.setRedirecting(true);
			context.channel().attr(StatefulPacketCodecProviderPair.attributeKey).get().setState(PlayStateCodecProvider.instance);
		} else if(packet.getOpcode() == LoginDisconnectPacket.opcode) {
			this.proxySession.disconnect(new PlayDisconnectPacket((((LoginDisconnectPacket) packet)).getJson()));
			channel.close();
		} else {
			this.proxySession.disconnectIfInitializing("Error: Protocol Mismatch");
			channel.close();
		}
		break;
	case INIT:
		if(packet.getOpcode() == 0x08) {
			this.state = ProxyState.CONNECTED;
			this.proxySession.setOutboundChannel(this.server, channel);
		}
	case CONNECTED:
		this.proxySession.outboundReceived(channel, packet);
		if(packet.getOpcode() == PlayDisconnectPacket.opcode) {
			this.state = ProxyState.DISCONNECTED;
		}
		break;
	default:
		break;
	}
}
 
源代码14 项目: styx   文件: HttpRequestOperation.java
public void write() {
    Channel originChannel = this.nettyConnection.channel();
    if (originChannel.isActive()) {
        io.netty.handler.codec.http.HttpRequest httpRequest = makeRequest(request);

        originChannel.writeAndFlush(httpRequest)
            .addListener(subscribeToRequestBody());
    } else {
        responseFromOriginFlux.error(new TransportLostException(originChannel.remoteAddress(), nettyConnection.getOrigin()));
    }
}
 
源代码15 项目: ViaVersion   文件: BungeeChannelInitializer.java
public BungeeChannelInitializer(ChannelInitializer<Channel> oldInit) {
    this.original = oldInit;
    try {
        this.method = ChannelInitializer.class.getDeclaredMethod("initChannel", Channel.class);
        this.method.setAccessible(true);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
}
 
源代码16 项目: PingAPI   文件: PingInjector.java
/**
 * Iterates through every open NetworkManager and adds my ChannelDuplexHandler subclass into the pipeline
 * This allows you to listen for outgoing packets and modify them before they are sent
 * 
 * The List of NetworkManager instances is converted to an array to avoid ConcurrentModificationExceptions
 * NullPointerExceptions, IllegalArgumentExceptions, and NoSuchElementException only occur if there is a massive amount of ping requests being sent to the server.
 * NullPointerExceptions are thrown when the pipeline has yet to be created. 
 * Since ping responses are handled on separate threads IllegalArgumentExceptions are thrown when this method is invoked at the same time on two different threads
 * This means the null check will be passed and this method will attempt to create a duplicate handler which throws this exception
 * NoSuchElementExceptions have a similar cause. They are caused when the "packet_handler" has yet to be added.
 * The best solution I could find is simply ignoring these exceptions
 */
public void injectOpenConnections() {
	try {
		Field field = ReflectUtils.getFirstFieldByType(NetworkManager.class, Channel.class);
		field.setAccessible(true);
		for(Object manager : networkManagers.toArray()) {
			Channel channel = (Channel) field.get(manager);
			if(channel.pipeline().context("pingapi_handler") == null && (channel.pipeline().context("packet_handler") != null)) {
				channel.pipeline().addBefore("packet_handler", "pingapi_handler", new DuplexHandler());
			}
		}
	} catch(IllegalAccessException e) {
		e.printStackTrace();
	} catch(NullPointerException | IllegalArgumentException | NoSuchElementException ignored) {}
}
 
源代码17 项目: panama   文件: ReverseShadowSocksProxy.java
public ReverseShadowSocksProxy(Channel clientChannel,
                               Callback finish,
                               ShadowSocksConfiguration shadowSocksConfiguration,
                               NioEventLoopGroup eventLoopGroup,
                               ShadowsocksRequestResolver requestResolver) {
    super(clientChannel, finish, shadowSocksConfiguration, eventLoopGroup, requestResolver);
}
 
源代码18 项目: crate   文件: PostgresWireProtocol.java
/**
 * Flush Message
 * | 'H' | int32 len
 * <p>
 * Flush forces the backend to deliver any data pending in it's output buffers.
 */
private void handleFlush(Channel channel) {
    try {
        // If we have deferred any executions we need to trigger a sync now because the client is expecting data
        // (That we've been holding back, as we don't eager react to `execute` requests. (We do that to optimize batch inserts))
        // The sync will also trigger a flush eventually if there are deferred executions.
        if (session.hasDeferredExecutions()) {
            session.sync();
        } else {
            channel.flush();
        }
    } catch (Throwable t) {
        Messages.sendErrorResponse(channel, t);
    }
}
 
源代码19 项目: pinpoint   文件: NettyClientRequestWrapper.java
@Override
public String getDestinationId() {
    if (this.channelHandlerContext != null) {
        final Channel channel = this.channelHandlerContext.channel();
        if (channel != null) {
            return NettyUtils.getEndPoint(channel.remoteAddress());
        }
    }
    return "Unknown";
}
 
源代码20 项目: proxyee-down   文件: NativeController.java
@RequestMapping("installCert")
public FullHttpResponse installCert(Channel channel, FullHttpRequest request) throws Exception {
  Map<String, Object> data = new HashMap<>();
  boolean status;
  if (OsUtil.isUnix() || OsUtil.isWindowsXP()) {
    if (!AppUtil.checkIsInstalledCert()) {
      ExtensionCertUtil.buildCert(AppUtil.SSL_PATH, AppUtil.SUBJECT);
    }
    Desktop.getDesktop().open(new File(AppUtil.SSL_PATH));
    status = true;
  } else {
    //再检测一次,确保不重复安装
    if (!AppUtil.checkIsInstalledCert()) {
      if (ExtensionCertUtil.existsCert(AppUtil.SUBJECT)) {
        //存在无用证书需要卸载
        ExtensionCertUtil.uninstallCert(AppUtil.SUBJECT);
      }
      //生成新的证书
      ExtensionCertUtil.buildCert(AppUtil.SSL_PATH, AppUtil.SUBJECT);
      //安装
      ExtensionCertUtil.installCert(new File(AppUtil.CERT_PATH));
      //检测是否安装成功,可能点了取消就没安装成功
      status = AppUtil.checkIsInstalledCert();
    } else {
      status = true;
    }
  }
  data.put("status", status);
  if (status && !PDownProxyServer.isStart) {
    new Thread(() -> {
      try {
        AppUtil.startProxyServer();
      } catch (IOException e) {
        LOGGER.error("Start proxy server error", e);
      }
    }).start();
  }
  return HttpHandlerUtil.buildJson(data);
}
 
源代码21 项目: servicetalk   文件: H2ParentConnectionContext.java
H2ParentConnectionContext(final Channel channel, final BufferAllocator allocator, final Executor executor,
                          final FlushStrategy flushStrategy, @Nullable final Long idleTimeoutMs,
                          final HttpExecutionStrategy executionStrategy,
                          final KeepAliveManager keepAliveManager) {
    super(channel, executor);
    this.executionContext = new DefaultHttpExecutionContext(allocator, fromNettyEventLoop(channel.eventLoop()),
            executor, executionStrategy);
    this.flushStrategyHolder = new FlushStrategyHolder(flushStrategy);
    this.idleTimeoutMs = idleTimeoutMs;
    this.keepAliveManager = keepAliveManager;
    // Just in case the channel abruptly closes, we should complete the onClosing Completable.
    onClose().subscribe(onClosing::onComplete);
}
 
@Test
public void failedConnectionAcquireNotifiesPromise() throws InterruptedException {
    IOException exception = new IOException();
    ChannelPool connectionPool = mock(ChannelPool.class);
    when(connectionPool.acquire()).thenReturn(new FailedFuture<>(loopGroup.next(), exception));

    ChannelPool pool = new Http2MultiplexedChannelPool(connectionPool, loopGroup.next(), null);

    Future<Channel> acquirePromise = pool.acquire().await();
    assertThat(acquirePromise.isSuccess()).isFalse();
    assertThat(acquirePromise.cause()).isEqualTo(exception);
}
 
源代码23 项目: Jupiter   文件: DefaultRegistry.java
private static boolean attachPublishEventOnChannel(RegisterMeta meta, Channel channel) {
    Attribute<ConcurrentSet<RegisterMeta>> attr = channel.attr(C_PUBLISH_KEY);
    ConcurrentSet<RegisterMeta> registerMetaSet = attr.get();
    if (registerMetaSet == null) {
        ConcurrentSet<RegisterMeta> newRegisterMetaSet = new ConcurrentSet<>();
        registerMetaSet = attr.setIfAbsent(newRegisterMetaSet);
        if (registerMetaSet == null) {
            registerMetaSet = newRegisterMetaSet;
        }
    }

    return registerMetaSet.add(meta);
}
 
源代码24 项目: Raincat   文件: SocketManager.java
public Channel getChannelByModelName(final String name) {
    if (CollectionUtils.isNotEmpty(clients)) {
        final Optional<Channel> first = clients.stream().filter(channel ->
                Objects.equals(channel.remoteAddress().toString(), name))
                .findFirst();
        return first.orElse(null);
    }
    return null;
}
 
源代码25 项目: netty-4.1.22   文件: SSLEngineTest.java
private static void verifyApplicationLevelProtocol(Channel channel, String expectedApplicationProtocol) {
    SslHandler handler = channel.pipeline().get(SslHandler.class);
    assertNotNull(handler);
    String appProto = handler.applicationProtocol();
    assertEquals(appProto, expectedApplicationProtocol);

    SSLEngine engine = handler.engine();
    if (engine instanceof Java9SslEngine) {
        // Also verify the Java9 exposed method.
        Java9SslEngine java9SslEngine = (Java9SslEngine) engine;
        assertEquals(expectedApplicationProtocol == null ? StringUtil.EMPTY_STRING : expectedApplicationProtocol,
                java9SslEngine.getApplicationProtocol());
    }
}
 
/**
 * B - S
 * @param channel
 * @param mqttMessage
 */
public void processUnSubBack(Channel channel, MqttMessage mqttMessage) {
	int messageId;
	if (mqttMessage instanceof MqttUnsubAckMessage) {
		MqttUnsubAckMessage mqttUnsubAckMessage = (MqttUnsubAckMessage) mqttMessage;
		messageId = mqttUnsubAckMessage.variableHeader().messageId();
	} else {
		MqttMessageIdVariableHeader o = (MqttMessageIdVariableHeader) mqttMessage.variableHeader();
		messageId = o.messageId();
		NettyLog.error("not UnsubAckMessage:{}", messageId);
	}
	this.consumerProcess.processUnSubBack(messageId);
}
 
源代码27 项目: reactor-netty   文件: UdpClientConfig.java
@Override
protected ChannelFactory<? extends Channel> connectionFactory(EventLoopGroup elg, boolean isDomainSocket) {
	if (isDomainSocket) {
		throw new UnsupportedOperationException();
	}
	if (isPreferNative()) {
		return () -> loopResources().onChannel(DatagramChannel.class, elg);
	}
	else {
		return () -> new NioDatagramChannel(family());
	}
}
 
源代码28 项目: servicetalk   文件: BuilderUtils.java
/**
 * Returns the correct Channel that wraps the given filedescriptor or {@code null} if not supported.
 *
 * @param group        the {@link EventLoopGroup} for which the class is needed
 * @param address      the filedescriptor to wrap.
 * @return the class that should be used for bootstrapping
 */
@Nullable
public static Channel socketChannel(EventLoopGroup group, FileDescriptorSocketAddress address) {
    if (useEpoll(group)) {
        return new EpollSocketChannel(address.getValue());
    }
    if (useKQueue(group)) {
        return new KQueueSocketChannel(address.getValue());
    }
    return null;
}
 
源代码29 项目: xrpc   文件: Call.java
public ListenableFuture<FullHttpResponse> execute() throws URISyntaxException {
  Preconditions.checkState(request != null);
  final SettableFuture<FullHttpResponse> error = SettableFuture.create();
  final SettableFuture<FullHttpResponse> response = SettableFuture.create();
  final ListenableFuture<ChannelFuture> connectFuture =
      connect(XUrl.inetSocket(uri), client.bootstrap(), buildRetryLoop());

  Futures.addCallback(
      connectFuture,
      new FutureCallback<ChannelFuture>() {
        @Override
        public void onSuccess(ChannelFuture result) {
          try {
            Channel channel = result.await().channel();
            channel.writeAndFlush(request);

            HttpResponseHandler responseHandler =
                (HttpResponseHandler) channel.pipeline().get("responseHandler");
            response.setFuture(responseHandler.response());
          } catch (InterruptedException e) {
            response.cancel(true);
            error.setException(e);
          }
        }

        @Override
        public void onFailure(Throwable t) {
          response.cancel(true);
          error.setException(t);
        }
      },
      MoreExecutors.directExecutor());

  if (response.isCancelled()) {
    return error;
  } else {
    return response;
  }
}
 
源代码30 项目: arcusplatform   文件: AbstractBounceHandler.java
@Nullable
protected String getIp(Channel channel) {
	SocketAddress address = channel.remoteAddress();
	if(address instanceof InetSocketAddress) {
		return ((InetSocketAddress) address).getAddress().getHostAddress();
	}
	else {
		logger.warn("Non inet socket address from client: {}", address);
		return null;
	}
}
 
源代码评论
动弹
沙发等你来抢
 类所在包
 类方法
 同包方法