apache-mina

Mina transmission frequency is too fast, causing received packets are merged


I'm using Apache Mina framework for communication between server and client, when I test the programe, I found if my transmission frequency is too fast, the received packets will merge to a big one, which should be each separate package.

My client used to send message, code like below:

public static void main(String[] args) {
        // IoConnector instance
        IoConnector connector = new NioSocketConnector();
        connector.setConnectTimeoutMillis(3000); // 连接超时时间

        // configure filters
        // connector.getFilterChain().addLast("coderc", new ProtocolCodecFilter(
        // new TextLineCodecFactory(Charset.forName("UTF-8"))));
        DefaultIoFilterChainBuilder builder = (DefaultIoFilterChainBuilder) connector.getFilterChainBuilder();
        Map<String, IoFilter> filters = new LinkedHashMap<>();
        filters.put("protocolCodecFilter", new ProtocolCodecFilter(new TcpCodecFactory()));
       
        filters.put("executor", new ExecutorFilter());
        filters.put("loggingFilter", new LoggingFilter());
        builder.setFilters(filters);
        connector.setFilterChainBuilder(builder);
        // set handler
        connector.setHandler(new TcpServerHandler());

        // connect to the server
        ConnectFuture future = connector.connect(new InetSocketAddress(address, port));
        future.awaitUninterruptibly(); // waiting for connection

        IoSession session = future.getSession();
        byte[] data = new byte[10];
        for (int i = 0; i < 100; ++i) {
            data[0] = (byte)i;  // first byte means the message sequence number
            for (int j = 1; j < 10; ++j) {
                data[j] = (byte) (j + 10);
            }
            // try {
            //     Thread.sleep(100);
            // } catch (InterruptedException e) {
            //     e.printStackTrace();
            // }
            session.write(data);
        }
        session.getCloseFuture().awaitUninterruptibly();    // wait for close
        connector.dispose();
        
    }    

When I comment the sleep code, which means I send message frequently, My received message will like below: enter image description here

The message sequence number is 0, 1, 6..., If I uncomment the sleep code, the message sequence number is 0, 1, 2, 3...

What's the difference? How to avoid the mixed packets in fast transmission?


Solution

  • You are using a TCP socket which is a stream channel versus UDP which is a message channel. Your messages are being combined because that is how TCP works on all platforms to effectively create as few network packets as possible.

    Unless the messages are out of order, then this is the expected behavior.