2009-12-07 95 views
1

我使用Apache 1.1.7米娜和Java 1.6。服務器循環發送三個消息序列給客戶端。有時兩組消息重疊。例如,我期待:麻煩同步線程與Apache米娜

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

我是什麼d錯了嗎?

回答

0

如果三個線程各自爲sendMessage()循環,那麼你會希望他們輸出線有時交錯,有時沒有。這是你描述的行爲。

我看你已經嘗試這些線程爲了同步輸出的每個消息的完整塊。那麼,什麼是可能會錯誤是每個線程都有它自己的session對象。您的線程必須共享他們同步的對象。

解決此問題的最簡單方法是刪除同步語句並使sendMessage() a synchronized method。雖然這可能不是很快。