io.netty.channel.ChannelHandlerContext#channel ( )源码实例Demo

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

源代码1 项目: GoPush   文件: NodeChannelInBoundHandler.java
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    Channel channel = ctx.channel();
    dataCenterChannelStore.isDcChannelToSave(channel);
    if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) {
        IdleStateEvent event = (IdleStateEvent) evt;
        if (event.state() == IdleState.ALL_IDLE) {
            //发送心跳
            channel.writeAndFlush(PING);
        }
        if (event.state() == IdleState.READER_IDLE) {
            //发送心跳
            channel.writeAndFlush(PING);
        }
        if (event.state() == IdleState.WRITER_IDLE) {
            channel.writeAndFlush(PING);
        }
    } else {
        super.userEventTriggered(ctx, evt);
    }
}
 
源代码2 项目: kcp-netty   文件: KcpRttClientHandler.java
@Override
public void channelActive(final ChannelHandlerContext ctx) {
    UkcpChannel kcpCh = (UkcpChannel) ctx.channel();
    kcpCh.conv(KcpRttClient.CONV); // set conv

    future = scheduleSrv.scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            ctx.write(rttMsg(++count));
            if (count >= rtts.length) {
                // finish
                future.cancel(true);
                ctx.write(rttMsg(-1));

            }
            ctx.flush();
        }
    }, KcpRttClient.RTT_INTERVAL, KcpRttClient.RTT_INTERVAL, TimeUnit.MILLISECONDS);
}
 
源代码3 项目: sofa-bolt   文件: ConnectionEventHandler.java
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object event) throws Exception {
    if (event instanceof ConnectionEventType) {
        switch ((ConnectionEventType) event) {
            case CONNECT:
                Channel channel = ctx.channel();
                if (null != channel) {
                    Connection connection = channel.attr(Connection.CONNECTION).get();
                    this.onEvent(connection, connection.getUrl().getOriginUrl(),
                        ConnectionEventType.CONNECT);
                } else {
                    logger
                        .warn("channel null when handle user triggered event in ConnectionEventHandler!");
                }
                break;
            default:
                break;
        }
    } else {
        super.userEventTriggered(ctx, event);
    }
}
 
@Override
public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
    // Send the received message to all channels but the current one.
    for (Channel c: channels) {
        if (c != ctx.channel()) {
            c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n');
        } else {
            c.writeAndFlush("[you] " + msg + '\n');
        }
    }

    // Close the connection if the client has sent 'bye'.
    if ("bye".equals(msg.toLowerCase())) {
        ctx.close();
    }
}
 
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
	if(ctx.channel()!= null && ctx.channel().remoteAddress()!=null){
		LOG.error("LionServerChannelInboundHanndler happen exception.remote address "+ctx.channel().remoteAddress().toString(),cause);
	}
    if(ctx != null){
        ctx.close();
    }
}
 
源代码6 项目: nuls-v2   文件: ServerChannelHandler.java
@Override
public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
    super.channelUnregistered(ctx);
    SocketChannel channel = (SocketChannel) ctx.channel();
    String nodeId = IpUtil.getNodeId(channel.remoteAddress());
    Attribute<Node> nodeAttribute = channel.attr(AttributeKey.valueOf("node-" + nodeId));

    Node node = nodeAttribute.get();
    if (node != null && node.getDisconnectListener() != null) {
        node.getDisconnectListener().action();
    }
    LoggerUtil.COMMON_LOG.info("Server Node is channelUnregistered:{}:{}", channel.remoteAddress().getHostString(), channel.remoteAddress().getPort());
}
 
源代码7 项目: proxy   文件: TCPChannelHandler.java
/**
 * 关闭用户连接
 */
private void closeChannle(ChannelHandlerContext ctx) {

    Channel channel = ctx.channel();

    if (channel != null && channel.isActive()) {
        channel.close();
    }
}
 
源代码8 项目: jstarcraft-core   文件: NettyTcpServerConnector.java
@Override
public void channelInactive(ChannelHandlerContext context) throws Exception {
    Channel channel = context.channel();
    InetSocketAddress address = InetSocketAddress.class.cast(channel.remoteAddress());
    CommunicationSession<Channel> session = sessionManager.getSession(address);
    // 将会话放到定时队列
    Instant now = Instant.now();
    Instant expire = now.plusMillis(expired);
    DelayElement<CommunicationSession<Channel>> element = new DelayElement<>(session, expire);
    queue.offer(element);
    super.channelInactive(context);
}
 
@Override
public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {

    final Channel channel = ctx.channel();

    if (cause instanceof SSLException) {
        //We can ignore SSL Exceptions, since the channel gets closed anyway.
        return;

    } else if (cause instanceof ClosedChannelException) {
        //We can ignore this because the channel is already closed
        return;

    } else if (cause instanceof IOException) {

        //We can ignore this because the channel is already closed because of an IO problem
        return;

    } else if (cause instanceof CorruptedFrameException) {

        //We can ignore this because the channel is already closed because of an IO problem
        eventLog.clientWasDisconnected(channel, "Illegal websocket data sent by client: " + cause.getMessage());
        channel.close();
        return;


    } else if (cause instanceof IllegalArgumentException) {

        //do not log IllegalArgumentException as error

    } else {
        log.error("An unexpected error occurred for client with IP {}: {}",
                ChannelUtils.getChannelIP(channel).or("UNKNOWN"), ExceptionUtils.getStackTrace(cause));
    }

    if (channel != null) {
        eventLog.clientWasDisconnected(channel, "Channel exception: " + cause.getMessage());
        channel.close();
    }
}
 
源代码10 项目: JLilyPad   文件: QueryTcpHandler.java
@Override
protected void channelRead0(ChannelHandlerContext context, String string) throws Exception {
	final Channel channel = context.channel();
	String response = this.generateResponse(string.toUpperCase());
	if(response != null) {
		channel.writeAndFlush(response).addListener(new ChannelFutureListener() {
			public void operationComplete(ChannelFuture future) throws Exception {
				channel.close();
			}
		});
	} else {
		channel.close();
	}
}
 
源代码11 项目: netty-4.1.22   文件: SocketStartTlsTest.java
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    channel = ctx.channel();
    if (!autoRead) {
        ctx.read();
    }
}
 
源代码12 项目: catalyst   文件: NettyHandler.java
@Override
public void channelInactive(ChannelHandlerContext context) throws Exception {
  Channel channel = context.channel();
  NettyConnection connection = removeConnection(channel);
  if (connection != null) {
    connection.handleClosed();
  }
}
 
@Override
public void channelActive(ChannelHandlerContext ctx) {
    clientChannel = ctx.channel();
}
 
源代码14 项目: learning-code   文件: ChatServerHandler.java
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    // 每当服务端收到客户端断开连接的时候
    Channel channel = ctx.channel();
    channel.writeAndFlush("client - " + channel.remoteAddress() + "退出了聊天室\n");
}
 
源代码15 项目: arcusplatform   文件: GatewayHandler.java
@Override
protected void channelRead0(@Nullable ChannelHandlerContext ctx, @Nullable Object msg) throws Exception {
   if (ctx == null || msg == null) {
      return;
   }

   lastPlatformMsg = System.nanoTime();
   Channel ch = ctx.channel();
   if (!handshaker.isHandshakeComplete()) {
      handshaker.finishHandshake(ch, (FullHttpResponse) msg);

      connected = true;
      handshakeFuture.setSuccess();
      return;
   }

   if (msg instanceof FullHttpResponse) {
      log.warn("unxpected full http response: {}", msg);
      ctx.close();
      return;
   }

   WebSocketFrame frame = (WebSocketFrame) msg;
   if (frame instanceof BinaryWebSocketFrame) {
      websocketFrameBuf.clear();
      websocketFrameBuf.writeBytes(frame.content());
   } else if (frame instanceof ContinuationWebSocketFrame){
      if (websocketFrameBuf.isReadable()) {
         websocketFrameBuf.writeBytes(frame.content());
      } else {
         log.warn("continuation frame received without initial frame.");
         ctx.close();
      }
   } else if (frame instanceof PingWebSocketFrame) {
      log.trace("received websocket ping request from platform");
      ctx.writeAndFlush(new PongWebSocketFrame(frame.content().retain()));
      lastHubMsg = System.nanoTime();
      return;
   } else if (frame instanceof PongWebSocketFrame) {
      log.trace("received websocket pong response from platform");
      return;
   } else if (frame instanceof CloseWebSocketFrame) {
      log.warn("received websocket close request");
      ctx.close();
      return;
   }

   if (frame.isFinalFragment()) {
      decodeHubFrame(ctx, websocketFrameBuf);
   }
}
 
源代码16 项目: netty4.0.27Learn   文件: SocketFileRegionTest.java
@Override
public void channelActive(ChannelHandlerContext ctx)
        throws Exception {
    channel = ctx.channel();
}
 
源代码17 项目: PacketLib   文件: TcpSession.java
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    if(ctx.channel() == this.channel) {
        this.disconnect("Connection closed.");
    }
}
 
源代码18 项目: netty4.0.27Learn   文件: SocketStartTlsTest.java
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    channel = ctx.channel();
}
 
源代码19 项目: momo-cloud-permission   文件: ChannelManager.java
public static String channelLongText(ChannelHandlerContext ctx) {
    Channel channel = ctx.channel();
    return channel.id().asLongText();
}
 
源代码20 项目: redant   文件: SessionHelper.java
/**
 * 判断session是否存在
 * @param context
 * @return
 */
public boolean containsSession(ChannelHandlerContext context){
    return context!=null && context.channel()!=null && context.channel().id()!=null && manager.sessionMap.get(context.channel().id())!=null;
}