Java Code Examples for io.netty.channel.ChannelHandlerContext#channel()

The following examples show how to use io.netty.channel.ChannelHandlerContext#channel() . 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: NodeChannelInBoundHandler.java    From GoPush with GNU General Public License v2.0 6 votes vote down vote up
@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);
    }
}
 
Example 2
Source File: KcpRttClientHandler.java    From kcp-netty with MIT License 6 votes vote down vote up
@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);
}
 
Example 3
Source File: ConnectionEventHandler.java    From sofa-bolt with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 4
Source File: SecureChatServerHandler.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example 5
Source File: LionServerChannelInboundHanndler.java    From lionrpc with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 6
Source File: ServerChannelHandler.java    From nuls-v2 with MIT License 5 votes vote down vote up
@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());
}
 
Example 7
Source File: TCPChannelHandler.java    From proxy with MIT License 5 votes vote down vote up
/**
 * 关闭用户连接
 */
private void closeChannle(ChannelHandlerContext ctx) {

    Channel channel = ctx.channel();

    if (channel != null && channel.isActive()) {
        channel.close();
    }
}
 
Example 8
Source File: NettyTcpServerConnector.java    From jstarcraft-core with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 9
Source File: ExceptionHandler.java    From hivemq-community-edition with Apache License 2.0 5 votes vote down vote up
@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();
    }
}
 
Example 10
Source File: NettyHandler.java    From catalyst with Apache License 2.0 5 votes vote down vote up
@Override
public void channelInactive(ChannelHandlerContext context) throws Exception {
  Channel channel = context.channel();
  NettyConnection connection = removeConnection(channel);
  if (connection != null) {
    connection.handleClosed();
  }
}
 
Example 11
Source File: QueryTcpHandler.java    From JLilyPad with GNU General Public License v3.0 5 votes vote down vote up
@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();
	}
}
 
Example 12
Source File: SocketStartTlsTest.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    channel = ctx.channel();
    if (!autoRead) {
        ctx.read();
    }
}
 
Example 13
Source File: ChannelManager.java    From momo-cloud-permission with Apache License 2.0 4 votes vote down vote up
public static String channelLongText(ChannelHandlerContext ctx) {
    Channel channel = ctx.channel();
    return channel.id().asLongText();
}
 
Example 14
Source File: SocketStartTlsTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    channel = ctx.channel();
}
 
Example 15
Source File: TcpSession.java    From PacketLib with MIT License 4 votes vote down vote up
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    if(ctx.channel() == this.channel) {
        this.disconnect("Connection closed.");
    }
}
 
Example 16
Source File: SocketFileRegionTest.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx)
        throws Exception {
    channel = ctx.channel();
}
 
Example 17
Source File: GatewayHandler.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
@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);
   }
}
 
Example 18
Source File: ChatServerHandler.java    From learning-code with Apache License 2.0 4 votes vote down vote up
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    // 每当服务端收到客户端断开连接的时候
    Channel channel = ctx.channel();
    channel.writeAndFlush("client - " + channel.remoteAddress() + "退出了聊天室\n");
}
 
Example 19
Source File: HttpProxyClientHandler.java    From azure-cosmosdb-java with MIT License 4 votes vote down vote up
@Override
public void channelActive(ChannelHandlerContext ctx) {
    clientChannel = ctx.channel();
}
 
Example 20
Source File: SessionHelper.java    From redant with Apache License 2.0 2 votes vote down vote up
/**
 * 判断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;
}