本文整理汇总了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);
}
示例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);
}
}
}
}
};
}
示例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);
}
示例4: channelActive
import io.netty.channel.ChannelHandlerContext; //导入方法依赖的package包/类
@Override
public void channelActive(ChannelHandlerContext ctx) {
ctx.writeAndFlush(Unpooled.EMPTY_BUFFER);
}
示例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;
}
示例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);
}
}
示例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));
}
}
示例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);
}
示例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);
}
}
}
示例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 ();
}
示例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;
}
}
示例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);
}
示例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;
}
}
示例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 );
}
示例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);
}