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

The following are Jave code examples for showing how to use writeAndFlush() 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: ClusterDeviceControlPlatform   File: MsgRecognitionOutBoundHandler.java   View Source Code Vote up 6 votes
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    SendableMsgContainer message = (SendableMsgContainer) msg;
    ByteBuf byteBuf = ctx.alloc().buffer();
    FrameMajorHeader header = message.getFrameHeader();
    byteBuf.writeByte(FrameSetting.MAJOR_FRAME_HEAD_1);
    byteBuf.writeByte(FrameSetting.MAJOR_FRAME_HEAD_2);
    byteBuf.writeByte(header.getGroupId());
    byteBuf.writeByte(header.getMsgId());
    byteBuf.writeByte(header.getDeviceId());
    byteBuf.writeByte(header.getBackupMsg());
    byteBuf.writeShort(header.getDataLength());

    List<ByteBuf> dataList = message.getDataList();
    dataList.forEach(byteBuf::writeBytes);
    ctx.writeAndFlush(byteBuf);
}
 
Example 2
Project: hekate   File: MulticastSeedNodeProvider.java   View Source Code Vote up 6 votes
private SimpleChannelInboundHandler<DatagramPacket> createListenerHandler(SeedNode thisNode, ByteBuf seedNodeInfo) {
    return new SimpleChannelInboundHandler<DatagramPacket>() {
        @Override
        public void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws Exception {
            ByteBuf buf = msg.content();

            if (buf.readableBytes() > 4 && buf.readInt() == Utils.MAGIC_BYTES) {
                MessageTYpe msgType = MessageTYpe.values()[buf.readByte()];

                if (msgType == MessageTYpe.DISCOVERY) {
                    String cluster = decodeUtf(buf);
                    InetSocketAddress address = decodeAddress(buf);

                    if (thisNode.cluster().equals(cluster) && !address.equals(thisNode.address())) {
                        onDiscoveryMessage(address);

                        DatagramPacket response = new DatagramPacket(seedNodeInfo.copy(), msg.sender());

                        ctx.writeAndFlush(response);
                    }
                }
            }
        }
    };
}
 
Example 3
Project: commelina   File: ChannelInboundHandlerRouterAdapter.java   View Source Code Vote up 6 votes
/**
 * 当客户端发送数据到服务器会触发此函数
 *
 * @param ctx
 * @param msg
 */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    final SocketASK ask = (SocketASK) msg;
    if (ask.getForward() >= SYSTEM_FORWARD_CODE.BOUNDARY_VALUE) {
        onRequest(ctx, ask);
        return;
    }

    if (ask.getForward() == SYSTEM_FORWARD_CODE.HEARTBEAT_VALUE) {
        // forward = 0 表示心跳
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("client id:{}, heartbeat ", ctx.channel().id());
        }
        ctx.writeAndFlush(ProtoBuffStatic.HEARTBEAT);
        ctx.fireChannelRead(ask);
        return;
    }
    systemOption(ctx, ask);
}
 
Example 4
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: AdminBrokerProcessor.java   View Source Code Vote up 5 votes
private RemotingCommand updateAndCreateTopic(ChannelHandlerContext ctx, RemotingCommand request) throws RemotingCommandException {
    final RemotingCommand response = RemotingCommand.createResponseCommand(null);
    final CreateTopicRequestHeader requestHeader =
        (CreateTopicRequestHeader) request.decodeCommandCustomHeader(CreateTopicRequestHeader.class);
    log.info("updateAndCreateTopic called by {}", RemotingHelper.parseChannelRemoteAddr(ctx.channel()));

    if (requestHeader.getTopic().equals(this.brokerController.getBrokerConfig().getBrokerClusterName())) {
        String errorMsg = "the topic[" + requestHeader.getTopic() + "] is conflict with system reserved words.";
        log.warn(errorMsg);
        response.setCode(ResponseCode.SYSTEM_ERROR);
        response.setRemark(errorMsg);
        return response;
    }

    try {
        response.setCode(ResponseCode.SUCCESS);
        response.setOpaque(request.getOpaque());
        response.markResponseType();
        response.setRemark(null);
        ctx.writeAndFlush(response);
    } catch (Exception e) {
        log.error("Failed to produce a proper response", e);
    }

    TopicConfig topicConfig = new TopicConfig(requestHeader.getTopic());
    topicConfig.setReadQueueNums(requestHeader.getReadQueueNums());
    topicConfig.setWriteQueueNums(requestHeader.getWriteQueueNums());
    topicConfig.setTopicFilterType(requestHeader.getTopicFilterTypeEnum());
    topicConfig.setPerm(requestHeader.getPerm());
    topicConfig.setTopicSysFlag(requestHeader.getTopicSysFlag() == null ? 0 : requestHeader.getTopicSysFlag());

    this.brokerController.getTopicConfigManager().updateTopicConfig(topicConfig);
    this.brokerController.registerBrokerAll(false, true);

    return null;
}
 
Example 5
Project: Cobweb   File: ShellRespHandler.java   View Source Code Vote up 5 votes
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ProcessData req = (ProcessData) msg;
    if (req.getType() == MessageType.SHELL_REQ.getValue()) {
        Command result = analysis(req.getCommand());
        //TODO add args
        ProcessData resp = buildShellResp(operation(result));
        ctx.writeAndFlush(resp);
    } else {
        ctx.fireChannelRead(msg);
    }
}
 
Example 6
Project: NSS   File: InRelayHandler.java   View Source Code Vote up 5 votes
@Override
public void channelActive(ChannelHandlerContext ctx) {
	ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
}
 
Example 7
Project: sctalk   File: IMLoginHandlerImpl.java   View Source Code Vote up 5 votes
@Override
public void queryPushShield(IMHeader header, MessageLite body, ChannelHandlerContext ctx) {
    long userId = super.getUserId(ctx);
	
	IMHeader resHeader = null;
    IMQueryPushShieldRsp queryPushShieldRsp = null;
	
	try {   	  		
		BaseModel<Integer> queryPushShieldRes  = loginService.queryPushShield(userId);
		
		queryPushShieldRsp = IMQueryPushShieldRsp.newBuilder()
				            .setUserId(userId)
				            .setShieldStatus(queryPushShieldRes.getData())
				            .setResultCode(queryPushShieldRes.getCode())
				            .build();    
		resHeader = header.clone();
		resHeader.setCommandId((short)LoginCmdID.CID_LOGIN_RES_QUERY_PUSH_SHIELD_VALUE);
		
		ctx.writeAndFlush(new IMProtoMessage<>(resHeader, queryPushShieldRsp));
	} catch(Exception e){
		
		logger.error("服务器端异常", e);

        // 异常时,处理(0:successed 1:failed)
        queryPushShieldRsp = IMQueryPushShieldRsp.newBuilder().setUserId(userId)
                .setResultCode(6).build();
        ctx.writeAndFlush(new IMProtoMessage<>(resHeader, queryPushShieldRsp));
	} 
}
 
Example 8
Project: Cobweb   File: WorkerProxyHandler.java   View Source Code Vote up 5 votes
private void takeNewTask(ChannelHandlerContext ctx){
    Epoch task;
    while(true) {
        logger.info("Waiting for task...");
        worker.waitForTask();
        logger.info("Trying to get a task...");
        task = worker.takeTask();
        if(task != null) {
            logger.info("Get task: " + task + " crawler start working...");
            currentTask = task;
            break;
        }
    }
    ProcessData.Builder builder = ProcessData.newBuilder();
    builder.setType(MessageType.CRAWLER_RESP.getValue());
    builder.setStatus(ProcessData.CrawlerStatus.RUNNING);
    builder.setUrlFilePath(configuration.WAITING_TASKS_URLS + "/" + task.getTaskName());
    builder.setUrlFileName(task.getTaskName());
    builder.setAttachment(ByteString.copyFrom(Integer.toString(task.getTaskData().getProgress()).getBytes()));
    ctx.writeAndFlush(builder.build());

    /* 拿到任务后会定时改变任务的mtime,防止被manager错误的重置 */
    heartBeat = ctx
            .channel()
            .eventLoop()
            .scheduleAtFixedRate(new HeartBeat(task.getTaskName()
                    , task.getTaskData().getUniqueMarkup(), ctx.channel()), 0
                    , configuration.WORKER_HEART_BEAT, TimeUnit.SECONDS);
}
 
Example 9
Project: sctalk   File: ClientUser.java   View Source Code Vote up 5 votes
public void broadcastWithOutMobile(IMProtoMessage<MessageLite> message, ChannelHandlerContext fromCtx) {
    for (ChannelHandlerContext conn: connMap.values()) {
        if (conn != fromCtx && CommonUtils.isPc(conn.attr(CLIENT_TYPE).get())) {
            logger.debug("发送消息> {}", conn.channel().remoteAddress());
            conn.writeAndFlush(message);
        }
    }
}
 
Example 10
Project: neoscada   File: RelpExceptionHandler.java   View Source Code Vote up 5 votes
@Override
public void exceptionCaught ( final ChannelHandlerContext ctx, final Throwable cause ) throws Exception
{
    logger.warn ( "Exception caught", cause );

    ctx.writeAndFlush ( ServerCloseMessage.INSTANCE );
    ctx.close ();
}
 
Example 11
Project: iotplatform   File: MqttTransportHandler.java   View Source Code Vote up 5 votes
private void processMqttMsg(ChannelHandlerContext ctx, MqttMessage msg) {
  // deviceSessionCtx.setChannel(ctx);
  // assetSessionCtx.setChannel(ctx);

  switch (msg.fixedHeader().messageType()) {
  case CONNECT:
    processConnect(ctx, (MqttConnectMessage) msg);
    break;
  case PUBLISH:
    processPublish(ctx, (MqttPublishMessage) msg);
    // System.out.println("write...");
    // ctx.write("just for test");
    break;
  case SUBSCRIBE:
    processSubscribe(ctx, (MqttSubscribeMessage) msg);
    break;
  case UNSUBSCRIBE:
    processUnsubscribe(ctx, (MqttUnsubscribeMessage) msg);
    break;
  case PINGREQ:
    if (checkConnected(ctx)) {
      ctx.writeAndFlush(new MqttMessage(new MqttFixedHeader(PINGRESP, false, AT_MOST_ONCE, false, 0)));
    }
    break;
  case DISCONNECT:
    if (checkConnected(ctx)) {
      processDisconnect(ctx);
    }
    break;
  }
}
 
Example 12
Project: nitmproxy   File: Http2BackendHandler.java   View Source Code Vote up 5 votes
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    LOGGER.info("[Client ({})] => [Server ({})] : {}",
                connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                msg);
    if (msg instanceof FullHttpRequest) {
        HttpMessage httpMessage = (HttpRequest) msg;
        httpMessage.headers().add(ExtensionHeaderNames.SCHEME.text(), "https");
    } else if (msg instanceof HttpObject) {
        throw new IllegalStateException("Cannot handle message: " + msg.getClass());
    }

    ctx.writeAndFlush(msg, promise);
}
 
Example 13
Project: nitmproxy   File: SocksProxyHandler.java   View Source Code Vote up 5 votes
@Override
protected void channelRead0(ChannelHandlerContext ctx, SocksMessage socksMessage)
        throws Exception {
    switch (socksMessage.version()) {
    case SOCKS4a:
        Socks4CommandRequest socksV4CmdRequest = (Socks4CommandRequest) socksMessage;
        if (socksV4CmdRequest.type() == Socks4CommandType.CONNECT) {
            onSocksSuccess(ctx, socksV4CmdRequest);
        } else {
            ctx.close();
        }
        break;
    case SOCKS5:
        if (socksMessage instanceof Socks5InitialRequest) {
            ctx.pipeline().addFirst(addChannelHandler(new Socks5CommandRequestDecoder()));
            ctx.writeAndFlush(new DefaultSocks5InitialResponse(Socks5AuthMethod.NO_AUTH));
        } else if (socksMessage instanceof Socks5PasswordAuthRequest) {
            ctx.pipeline().addFirst(addChannelHandler(new Socks5CommandRequestDecoder()));
            ctx.writeAndFlush(new DefaultSocks5PasswordAuthResponse(Socks5PasswordAuthStatus.SUCCESS));
        } else if (socksMessage instanceof Socks5CommandRequest) {
            Socks5CommandRequest socks5CmdRequest = (Socks5CommandRequest) socksMessage;
            if (socks5CmdRequest.type() == Socks5CommandType.CONNECT) {
                onSocksSuccess(ctx, socks5CmdRequest);
            } else {
                ctx.close();
            }
        } else {
            ctx.close();
        }
        break;
    case UNKNOWN:
        ctx.close();
        break;
    }
}
 
Example 14
Project: neoscada   File: DataModuleHandler.java   View Source Code Vote up 5 votes
@Override
public void requestStartData ()
{
    final ChannelHandlerContext ctx = this.ctx;
    if ( ctx == null )
    {
        return;
    }

    ctx.writeAndFlush ( DataTransmissionMessage.REQUEST_START );
}
 
Example 15
Project: QDrill   File: BasicServer.java   View Source Code Vote up 4 votes
@Override
protected void consumeHandshake(ChannelHandlerContext ctx, T inbound) throws Exception {
  OutboundRpcMessage msg = new OutboundRpcMessage(RpcMode.RESPONSE, this.handshakeType, coordinationId,
      getHandshakeResponse(inbound));
  ctx.writeAndFlush(msg);
}
 
Example 16
Project: jsf-sdk   File: RestRequestHandler.java   View Source Code Vote up 4 votes
private void send100Continue(ChannelHandlerContext ctx)
{
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, CONTINUE);
    ctx.writeAndFlush(response);
}
 
Example 17
Project: sds   File: SocketEventServiceImpl.java   View Source Code Vote up 4 votes
@Override
public void onReadListener(ChannelHandlerContext ctx, String uniqueKey, Object msg) {

    byte[] datas = (byte[]) msg;

    String modelName = socketControl.getModelName();

    String str = new String(datas);

    logger.info("onReadListener--> modelName->"+modelName+",uniqueKey->"+uniqueKey+",msg->"+str);

    //重置心跳时间规则
    if("heartTime".equals(str)) {
        socketControl.resetHeartTime(ctx.channel(),20);
    }

    ctx.writeAndFlush(datas);
}
 
Example 18
Project: ss-java   File: RelayHandler.java   View Source Code Vote up 4 votes
@Override
public void channelActive(ChannelHandlerContext ctx) {
    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
}
 
Example 19
Project: Cobweb   File: WorkerProxyHandler.java   View Source Code Vote up 4 votes
private void process(ChannelHandlerContext ctx, ProcessData data){
    String taskPath = ZNodeStaticSetting.NEW_TASK_PATH + data.getUrlFileName();
    ProcessData.CrawlerStatus status = data.getStatus();
    ProcessData.Builder builder = ProcessData.newBuilder();
    switch (status){
        case NULL:
            currentTask = null;
            logger.warn("Give up the task: " + taskPath);
            /*
                TODO 目前暂时将放弃的任务放入黑名单,后面会设置定时器将其移除
             */
            Worker.addToBlackList(new File(taskPath).getName());
            worker.discardTask(taskPath);
            break;
        case READY:
            if(currentTask != null){
                builder.setType(MessageType.CRAWLER_RESP.getValue());
                builder.setStatus(ProcessData.CrawlerStatus.RUNNING);
                builder.setUrlFilePath(configuration.WAITING_TASKS_URLS +
                        "/" + currentTask.getTaskName());
                builder.setUrlFileName(currentTask.getTaskName());
                ctx.writeAndFlush(builder.build());
                break;
            }
            takeNewTask(ctx);
            break;
        case FINNISHED:
            currentTask = null;
            heartBeat.cancel(true);
            worker.finishTask(taskPath);
            takeNewTask(ctx);
            break;
        case WAITING:
            break;
        /*
            TODO 任务文件有问题,放弃任务并且移除这个任务
            case ERROR
         */
        default:
            break;
    }
}
 
Example 20
Project: message-broker   File: ConnectionOpen.java   View Source Code Vote up 4 votes
@Override
public void handle(ChannelHandlerContext ctx, AmqpConnectionHandler connectionHandler) {
    ctx.writeAndFlush(new ConnectionOpenOk());
}