views:

100

answers:

1

I'm using Apache Mina 1.1.7 and Java 1.6. The server sends a sequence of three messages to the client in loop. Sometimes two sets of messages overlap. For example, I am expecting:

++ recv: MSGHEAD 
++ recv: message body 1
++ recv: .

++ recv: MSGHEAD 
++ recv: message body 2
++ recv: .

but I get this instead:

++ recv: MSGHEAD
++ recv: MSGHEAD 
++ recv: message body 1
++ recv: .
++ recv: message body 2
++ recv: .

Here is my server configuration:

    SocketAcceptor acceptor = new SocketAcceptor();
    SocketAcceptorConfig config = new SocketAcceptorConfig();
    config.setThreadModel(ThreadModel.MANUAL);
    if (true) {
        SSLContextFactory factory = new SSLContextFactory();
        config.getFilterChain().addLast("sslFilter", new SSLFilter(factory.getInstance(true)));
    }

    System.out.println(config.getFilterChain().toString());
    config.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8")) ));
    config.getFilterChain().addLast("to-message", new ToMessageIoFilter());

    config.getSessionConfig().setReuseAddress( true );
    config.getSessionConfig().setTcpNoDelay(true);
    acceptor.bind( new InetSocketAddress(PORT), new MinaServerHandler(new MinaConnectionFactory()), config );
}

Here is how I send out a sequence of messages:

public  void sendMessage(String msg) throws IOException {
    synchronized(session){
        writeLine("MSGHEAD");
        writeLine(msg);
        writeLine(".");
    }
}

private void writeLine(String line) {
    WriteFuture w=session.write(line);
}

What am I doing wrong?

A: 

If three threads are each in loops of sendMessage() then you would expect them to output the lines sometimes interleaved, sometimes not. Which is the behavior you describe.

I do see you've attempted to synchronize those threads in order to output full blocks of messages each. So what is probably going wrong is that each thread has it's own session object. Your threads must share the object on which they synchronize.

The simplest way to address this is to remove the synchronized statement and make sendMessage() a synchronized method. This might not be very speedy though.

dlamblin