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

The following are Jave code examples for showing how to use channel() of the io.netty.channel.ChannelHandlerContext class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: util4j   File: NettyTextWebSocketClient.java   View Source Code Vote up 6 votes
/**
	 * 适配
	 */
	@Override
	protected ChannelHandler fixHandlerBeforeConnect(final ChannelHandler handler) {
		ChannelHandler result=new ShareableChannelInboundHandler() {
			@Override
			public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
				Channel ch=ctx.channel();
				ch.pipeline().addLast(new HttpClientCodec());
            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
				ctx.pipeline().remove(this);//移除当前handler
				ctx.pipeline().fireChannelRegistered();//重新从第一个handler抛出事件
			}
		};
//		ChannelInitializer<SocketChannel> result=new ChannelInitializer<SocketChannel>() {
//            @Override
//            protected void initChannel(SocketChannel ch) {
//            	ch.pipeline().addLast(new HttpClientCodec());
//            	ch.pipeline().addLast(new HttpObjectAggregator(64*1024));
//            	ch.pipeline().addLast(new WebSocketClientProtocolHandler(WebSocketClientHandshakerFactory.newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())));
//            	ch.pipeline().addLast(new WebSocketConnectedClientHandler(handler));
//            }
//        };
        return result;
	}
 
Example 2
Project: jsf-sdk   File: ServerChannelHandler.java   View Source Code Vote up 6 votes
@Override
public void channelActive(final ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    //logger.info("connected from {}", NetUtils.channelToString(channel.remoteAddress(), channel.localAddress()));
    BaseServerHandler.addChannel(channel);
    if (connectListeners != null) {
        serverHandler.getBizThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                for (ConnectListener connectListener : connectListeners) {
                    try {
                        connectListener.connected(ctx);
                    } catch (Exception e) {
                        logger.warn("Failed to call connect listener when channel active", e);
                    }
                }
            }
        });
    }
}
 
Example 3
Project: UnknownPandaServer   File: NetworkManager.java   View Source Code Vote up 5 votes
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    super.channelActive(ctx);
    this.channel = ctx.channel();

    UnknownPandaServer.getLogger().info("Channel active: " + this.channel.remoteAddress());
}
 
Example 4
Project: angel   File: WorkerPool.java   View Source Code Vote up 5 votes
/**
 * Send back the result
 * @param ctx channel context
 * @param result rpc result
 */
private void send(ChannelHandlerContext ctx, Object result) {
  int seqId = 0;
  Channel ch = ctx.channel();

  try {
    seqId = ((ByteBuf) result).readInt();
    ((ByteBuf) result).resetReaderIndex();
    AtomicBoolean channelInUse = channelStates.get(ctx);
    if (channelInUse == null) {
      return;
    }
    long startTs = System.currentTimeMillis();
    while (true) {
      if (channelInUse.compareAndSet(false, true)) {
        ctx.writeAndFlush(result);
        channelInUse.set(false);
        LOG.debug(
          "send response buf=" + result + ",channel ctx=" + ctx.channel() + ", seqId=" + seqId
            + " use time=" + (System.currentTimeMillis() - startTs));
        return;
      }
      Thread.sleep(10);
    }
  } catch (Throwable ex) {
    LOG.error("send response of request failed, request seqId=" + seqId + ", channel=" + ch, ex);
  }
}
 
Example 5
Project: util4j   File: AbstractListenerHandler.java   View Source Code Vote up 5 votes
@Override
public final void channelInactive(ChannelHandlerContext ctx)throws Exception 
{
	Channel channel=ctx.channel();
	JConnection connection = findConnection(channel);
	if (connection != null) 
	{
		listener.connectionClosed(connection);
	} else 
	{
		log.error(ctx.channel() + ":not found NettyConnection Created.");
	}
	super.channelInactive(ctx);
}
 
Example 6
Project: TFWebSock   File: SubscriptionHandler.java   View Source Code Vote up 5 votes
public void disconnected(ChannelHandlerContext ctx)
{
    JSON.ClientDisconnectMessage dmsg = new JSON.ClientDisconnectMessage( ctx.channel( ));
    try {
        outQ.put( dmsg);
    }
    catch (InterruptedException e) {
        logr.info( "StockTickerMessageHandler.disconnected: outQ.put( ) failed for "
                                                            + ctx + "\n" + e.toString( ));
    }
}
 
Example 7
Project: GoPush   File: MultiMessageToDeviceHandler.java   View Source Code Vote up 5 votes
@Override
public void call(ChannelHandlerContext ctx, MultiMessageToDeviceReq message) {
    //找寻到对应设备的channel 将消息全部推送给这个设备
    if (message != null) {
        pushSender.send(message.getDevice(), PushReq.builder().msgs(message.getMessages()).build());
        Channel channel = ctx.channel();
        channel.writeAndFlush(MultiMessageToDeviceResp.builder().result(NodeMessageEnum.OK.getCode()).build().encode());
    }
}
 
Example 8
Project: candlelight   File: NetworkDispatcher.java   View Source Code Vote up 5 votes
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception
{
	super.channelActive(ctx);

	this.channel = ctx.channel();
	this.address = this.channel.remoteAddress();

	//Try to handshake?
}
 
Example 9
Project: Cobweb   File: LoginAuthReqHandler.java   View Source Code Vote up 5 votes
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    if(initMessage != null){
        ctx.writeAndFlush(initMessage);
    } else {
        logger.info("build connection success.");
        channel[0] = ctx.channel();
        ProcessData.Builder builder = ProcessData.newBuilder();
        builder.setType(MessageType.HEART_BEAT_REQ.getValue());
        ctx.fireChannelRead(builder.build());
    }
}
 
Example 10
Project: jsf-sdk   File: TelnetChannelHandler.java   View Source Code Vote up 5 votes
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    Channel channel = ctx.channel();
    LOGGER.info("Disconnected telnet from {}", NetUtils.channelToString(channel.remoteAddress(), channel.localAddress()));
    BaseServerHandler.removeChannel(channel);
    charsetMap.remove(channel);
    ALLOW_INVOKE_CHANNELS.remove(channel);
}
 
Example 11
Project: iotplatform   File: MqttTransportHandler.java   View Source Code Vote up 4 votes
private void processSubscribe(ChannelHandlerContext ctx, MqttSubscribeMessage mqttMsg) {
  if (!checkConnected(ctx)) {
    return;
  }
  log.trace("[{}] Processing subscription [{}]!", sessionId, mqttMsg.variableHeader().messageId());
  List<Integer> grantedQoSList = new ArrayList<>();
  for (MqttTopicSubscription subscription : mqttMsg.payload().topicSubscriptions()) {
    String topicName = subscription.topicName();
    // TODO: handle this qos level.
    MqttQoS reqQoS = subscription.qualityOfService();
    try {
      if (topicName.equals(DEVICE_ATTRIBUTES_TOPIC)) {
        // AdaptorToSessionActorMsg msg =
        // adaptor.convertToActorMsg(deviceSessionCtx,
        // SUBSCRIBE_ATTRIBUTES_REQUEST,
        // mqttMsg);
        // BasicToDeviceActorSessionMsg basicToDeviceActorSessionMsg = new
        // BasicToDeviceActorSessionMsg(
        // deviceSessionCtx.getDevice(), msg);
        // processor.process(basicToDeviceActorSessionMsg);
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else if (topicName.equals(DEVICE_RPC_REQUESTS_SUB_TOPIC)) {
        // AdaptorToSessionActorMsg msg =
        // adaptor.convertToActorMsg(deviceSessionCtx,
        // SUBSCRIBE_RPC_COMMANDS_REQUEST,
        // mqttMsg);
        // processor.process(new
        // BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(), msg));
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else if (topicName.equals(DEVICE_RPC_RESPONSE_SUB_TOPIC)) {
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else if (topicName.equals(DEVICE_ATTRIBUTES_RESPONSES_TOPIC)) {
        deviceSessionCtx.setAllowAttributeResponses();
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else if (topicName.equals(DEVICE_TELEMETRY_TOPIC)) {
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else {
        log.warn("[{}] Failed to subscribe to [{}][{}]", sessionId, topicName, reqQoS);
        grantedQoSList.add(FAILURE.value());
      }
      ChannelEntity channelEntity = new TcpChannelEntity(ctx.channel());
      MemoryMetaPool.registerTopic(channelEntity, topicName);
    } catch (Exception e) {
      e.printStackTrace();
      log.warn("[{}] Failed to subscribe to [{}][{}]", sessionId, topicName, reqQoS);
      grantedQoSList.add(FAILURE.value());
    }
  }

  ctx.writeAndFlush(createSubAckMessage(mqttMsg.variableHeader().messageId(), grantedQoSList));
}
 
Example 12
Project: CloudLand-Server   File: NetworkServer.java   View Source Code Vote up 4 votes
public CLSession openSession(String identifier, ChannelHandlerContext ctx) {
    CLSession session = new CLSession(this, identifier, (SocketChannel) ctx.channel());
    this.players.put(identifier, session);
    return session;
}
 
Example 13
Project: util4j   File: NettyConnection.java   View Source Code Vote up 4 votes
public NettyConnection(ChannelHandlerContext ctx) {
	this.ctx=ctx;
	this.channel=ctx.channel();
	this.id=getChannelId(channel);
	channel.attr(CHANNEL_KEY).set(this);
}
 
Example 14
Project: guereza   File: ServerHandler.java   View Source Code Vote up 4 votes
@Override
public void handlerAdded(final ChannelHandlerContext ctx) {
    final Channel incoming = ctx.channel();
    LOGGER.info("Handling connection");
    channels.add(incoming);
}
 
Example 15
Project: kcp-netty   File: EchoServerHandler.java   View Source Code Vote up 4 votes
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
    UkcpChannel kcpCh = (UkcpChannel) ctx.channel();
    kcpCh.conv(EchoServer.CONV);
}
 
Example 16
Project: GoPush   File: DeviceDockedHandler.java   View Source Code Vote up 4 votes
@Override
public void call(ChannelHandlerContext ctx, DeviceDockedReq message) {
    Channel channel = ctx.channel();
    channel.writeAndFlush(DeviceDockedResp.builder().result(NodeMessageEnum.OK.getCode()).build().encode());
    log.debug("receive DeviceDockedReq, channel:{}", channel);
}
 
Example 17
Project: push   File: ServerHandler.java   View Source Code Vote up 4 votes
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception { // (5)
	Channel incoming = ctx.channel();
	System.out.println("SimpleChatClient:" + incoming.remoteAddress() + "在线");
}
 
Example 18
Project: iothub   File: MqttTransportHandler.java   View Source Code Vote up 4 votes
private void processSubscribe(ChannelHandlerContext ctx, MqttSubscribeMessage mqttMsg) {
  if (!checkConnected(ctx)) {
    return;
  }
  log.trace("[{}] Processing subscription [{}]!", sessionId, mqttMsg.variableHeader().messageId());
  List<Integer> grantedQoSList = new ArrayList<>();
  for (MqttTopicSubscription subscription : mqttMsg.payload().topicSubscriptions()) {
    String topicName = subscription.topicName();
    // TODO: handle this qos level.
    MqttQoS reqQoS = subscription.qualityOfService();
    try {
      if (topicName.equals(DEVICE_ATTRIBUTES_TOPIC)) {
        // AdaptorToSessionActorMsg msg =
        // adaptor.convertToActorMsg(deviceSessionCtx,
        // SUBSCRIBE_ATTRIBUTES_REQUEST,
        // mqttMsg);
        // BasicToDeviceActorSessionMsg basicToDeviceActorSessionMsg = new
        // BasicToDeviceActorSessionMsg(
        // deviceSessionCtx.getDevice(), msg);
        // processor.process(basicToDeviceActorSessionMsg);
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else if (topicName.equals(DEVICE_RPC_REQUESTS_SUB_TOPIC)) {
        // AdaptorToSessionActorMsg msg =
        // adaptor.convertToActorMsg(deviceSessionCtx,
        // SUBSCRIBE_RPC_COMMANDS_REQUEST,
        // mqttMsg);
        // processor.process(new
        // BasicToDeviceActorSessionMsg(deviceSessionCtx.getDevice(), msg));
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else if (topicName.equals(DEVICE_RPC_RESPONSE_SUB_TOPIC)) {
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else if (topicName.equals(DEVICE_ATTRIBUTES_RESPONSES_TOPIC)) {
        deviceSessionCtx.setAllowAttributeResponses();
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else if (topicName.equals(DEVICE_TELEMETRY_TOPIC)) {
        grantedQoSList.add(getMinSupportedQos(reqQoS));
      } else {
        log.warn("[{}] Failed to subscribe to [{}][{}]", sessionId, topicName, reqQoS);
        grantedQoSList.add(FAILURE.value());
      }
      ChannelEntity channelEntity = new TcpChannelEntity(ctx.channel());
      MemoryMetaPool.registerTopic(channelEntity, topicName);
    } catch (Exception e) {
      e.printStackTrace();
      log.warn("[{}] Failed to subscribe to [{}][{}]", sessionId, topicName, reqQoS);
      grantedQoSList.add(FAILURE.value());
    }
  }

  ctx.writeAndFlush(createSubAckMessage(mqttMsg.variableHeader().messageId(), grantedQoSList));
}
 
Example 19
Project: GoPush   File: MultiMessageToDeviceHandler.java   View Source Code Vote up 4 votes
@Override
public void call(ChannelHandlerContext ctx, MultiMessageToDeviceResp message) {
    Channel channel = ctx.channel();

    log.debug("receive MessageToMultiDeviceResp, channel:{}", channel);
}
 
Example 20
Project: redant   File: SessionHelper.java   View Source Code Vote up 2 votes
/**
 * 判断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;
}