TCP Netty Ensure message received

2019-04-02 00:52发布

问题:

I am creating client-server system, that should be able to work in ustable network. It assumes that connection could be broken at one time, and then system must reconnect and continue it's work. I'am using Netty and stucked with a problem: how do we know that message, which we sent, was received by another host?

I was thinking, for this purpose ChannelFuture could be used, and i can simply try to send message again if it fails in attached future listener:

ChannelFuture fut = channel.write(message);
fut.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
                LOGGER.error("Message send failed. Message: " + message, future.getCause());
                //Queue message to be send after reconnect
            } 
        }
});

But when i done, i noticed, that listener never prints error. (I tested this by unpluging from network when system hardly works) Also i noticed that all futures for messages, which i send, comes into 'done' state and there is way to no ensure message was received (not using acknowledge messages)

As i know, TCP protocol guaranties that message would be received, and when working with it we can know which send packages reached their destination and which not. I can't believe that Netty does not allow to know it.

Is there a good way to know that message was delivered?

回答1:

You're misunderstanding TCP. TCP does not guarantee that your message is received. It provides a reliable, ordered byte stream. It doesn't know anything about your message and cannot tell you when it has been received by the remote host. Therefore neither can Netty. Netty can only tell you that your message has been written to the operating system buffers before it is transmitted. This is what your code is detecting.

To be sure that your message has been received, the receiver must send back an explicit acknowledgement. The best way to achieve this depends on the expected behaviour of your protocol but usually involves maintaining a table of all messages that have been sent but not yet acknowledged.



回答2:

All your future does is write the message to the network.

To have guaranteed reception you must either implement an acknowledgment or use message numbers and resend requests.



标签: java tcp netty