1

我正在使用 Apache Mina 1.1.7 和 Java 1.6。服务器循环向客户端发送三个消息的序列。有时两组消息重叠。例如,我期待:

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

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

但我得到了这个:

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

这是我的服务器配置:

    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 );
}

以下是我发送一系列消息的方式:

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

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

我究竟做错了什么?

4

1 回答 1

0

如果三个线程都在循环中,sendMessage()那么您会期望它们输出有时交错的行,有时不输出。这是您描述的行为。

我确实看到您已尝试同步这些线程,以便分别输出完整的消息块。所以可能出了问题的是每个线程都有自己的session对象。您的线程必须共享它们同步的对象。

解决这个问题的最简单方法是删除同步语句并创建sendMessage()一个同步方法。不过,这可能不是很快。

于 2009-12-08T01:52:35.447 回答