當前位置: 首頁>>代碼示例>>Java>>正文


Java ChannelHandlerContext.writeAndFlush方法代碼示例

本文整理匯總了Java中io.netty.channel.ChannelHandlerContext.writeAndFlush方法的典型用法代碼示例。如果您正苦於以下問題:Java ChannelHandlerContext.writeAndFlush方法的具體用法?Java ChannelHandlerContext.writeAndFlush怎麽用?Java ChannelHandlerContext.writeAndFlush使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在io.netty.channel.ChannelHandlerContext的用法示例。


在下文中一共展示了ChannelHandlerContext.writeAndFlush方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: write

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
@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);
}
 
開發者ID:bitkylin,項目名稱:ClusterDeviceControlPlatform,代碼行數:18,代碼來源:MsgRecognitionOutBoundHandler.java

示例2: createListenerHandler

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
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);
                    }
                }
            }
        }
    };
}
 
開發者ID:hekate-io,項目名稱:hekate,代碼行數:26,代碼來源:MulticastSeedNodeProvider.java

示例3: channelRead

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
/**
 * 當客戶端發送數據到服務器會觸發此函數
 *
 * @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);
}
 
開發者ID:freedompy,項目名稱:commelina,代碼行數:26,代碼來源:ChannelInboundHandlerRouterAdapter.java

示例4: channelActive

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
@Override
public void channelActive(ChannelHandlerContext ctx) {
	ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
}
 
開發者ID:breakEval13,項目名稱:NSS,代碼行數:5,代碼來源:InRelayHandler.java

示例5: updateAndCreateTopic

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
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;
}
 
開發者ID:lirenzuo,項目名稱:rocketmq-rocketmq-all-4.1.0-incubating,代碼行數:37,代碼來源:AdminBrokerProcessor.java

示例6: channelRead

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
@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);
    }
}
 
開發者ID:xiongbeer,項目名稱:Cobweb,代碼行數:13,代碼來源:ShellRespHandler.java

示例7: queryPushShield

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
@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));
	} 
}
 
開發者ID:ccfish86,項目名稱:sctalk,代碼行數:30,代碼來源:IMLoginHandlerImpl.java

示例8: takeNewTask

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
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);
}
 
開發者ID:xiongbeer,項目名稱:Cobweb,代碼行數:30,代碼來源:WorkerProxyHandler.java

示例9: broadcastWithOutMobile

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
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);
        }
    }
}
 
開發者ID:ccfish86,項目名稱:sctalk,代碼行數:9,代碼來源:ClientUser.java

示例10: exceptionCaught

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
@Override
public void exceptionCaught ( final ChannelHandlerContext ctx, final Throwable cause ) throws Exception
{
    logger.warn ( "Exception caught", cause );

    ctx.writeAndFlush ( ServerCloseMessage.INSTANCE );
    ctx.close ();
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:9,代碼來源:RelpExceptionHandler.java

示例11: processMqttMsg

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
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;
  }
}
 
開發者ID:osswangxining,項目名稱:iotplatform,代碼行數:32,代碼來源:MqttTransportHandler.java

示例12: write

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
@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);
}
 
開發者ID:chhsiao90,項目名稱:nitmproxy,代碼行數:15,代碼來源:Http2BackendHandler.java

示例13: channelRead0

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
@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;
    }
}
 
開發者ID:chhsiao90,項目名稱:nitmproxy,代碼行數:36,代碼來源:SocksProxyHandler.java

示例14: requestStartData

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
@Override
public void requestStartData ()
{
    final ChannelHandlerContext ctx = this.ctx;
    if ( ctx == null )
    {
        return;
    }

    ctx.writeAndFlush ( DataTransmissionMessage.REQUEST_START );
}
 
開發者ID:eclipse,項目名稱:neoscada,代碼行數:12,代碼來源:DataModuleHandler.java

示例15: consumeHandshake

import io.netty.channel.ChannelHandlerContext; //導入方法依賴的package包/類
@Override
protected void consumeHandshake(ChannelHandlerContext ctx, T inbound) throws Exception {
  OutboundRpcMessage msg = new OutboundRpcMessage(RpcMode.RESPONSE, this.handshakeType, coordinationId,
      getHandshakeResponse(inbound));
  ctx.writeAndFlush(msg);
}
 
開發者ID:skhalifa,項目名稱:QDrill,代碼行數:7,代碼來源:BasicServer.java


注:本文中的io.netty.channel.ChannelHandlerContext.writeAndFlush方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。