gpt4 book ai didi

java - 如何让 netty channel.writeAndFlush() 在没有 TCP ACK 响应时抛出异常

转载 作者:行者123 更新时间:2023-11-29 04:47:07 26 4
gpt4 key购买 nike

我正在使用 Netty4 框架开发一个 IM 服务器。同时,我使用名为channel.writeAndFlush() 的方法向客户端发送消息。但是,当手机端的客户端socket异常关闭时,比如关闭网络连接,或者在设备上开启飞行模式,netty4 frame找不到对应的channel inactive。此外,writeAndFlush()方法返回的ChannelGroupFuture通过ChannelGroupFuture.isSuccess()方法报告发送结果成功。那么,为什么 ChannelGroupFuture 没有返回发送失败而没有抛出任何异常?

ChannelGroupFuture future = connectionService.sendMessageToUser(msgBase, toUid).sync();

future.addListeners(new ChannelGroupFutureListener(){

@Override
public void operationComplete(ChannelGroupFuture future)
throws Exception {
if(future.isDone() && future.isSuccess()){
chatMessageService.saveSentChatMessage(msgBase);
} else if(!future.isSuccess()){
chatMessageService.saveUnsentChatMessage(msgBase);
}
});

public ChannelGroupFuture writeAndFlush(Object message, ChannelMatcher matcher) {
if (message == null) {
throw new NullPointerException("message");
}
if (matcher == null) {
throw new NullPointerException("matcher");
}
if(matcher instanceof AttributeChannelMatcher){
Map<Channel, ChannelFuture> futures = new LinkedHashMap<Channel, ChannelFuture>(1);
AttributeChannelMatcher<T> attributeMatcher = (AttributeChannelMatcher<T>) matcher;
Channel c = nonServerChannelMap.get(attributeMatcher.getAttributeKeyValue());

futures.put(c, c.writeAndFlush(safeDuplicate(message)));
ReferenceCountUtil.release(message);
return new DefaultChannelGroupFuture(this, futures, executor);
}else{
Map<Channel, ChannelFuture> futures = new LinkedHashMap<Channel, ChannelFuture>(size());

for (Channel c : nonServerChannelMap.values()) {
if (matcher.matches(c)) {
futures.put(c, c.writeAndFlush(safeDuplicate(message)));
}
}
ReferenceCountUtil.release(message);
return new DefaultChannelGroupFuture(this, futures, executor);
}
}

最佳答案

你不能。 TCP 写入相对于应用程序是异步的。他们在返回之前不会等待 ACK。发送端有一个发送缓冲区,接收端有一个接收缓冲区。所有这一切意味着,在您检测到断开的连接之前,可能需要多次写入和相当多的几秒钟。

关于java - 如何让 netty channel.writeAndFlush() 在没有 TCP ACK 响应时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36718304/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com