当前位置: 代码迷 >> Java相关 >> mina框架接收数据包连在一块有关问题
  详细解决方案

mina框架接收数据包连在一块有关问题

热度:9807   发布时间:2013-02-25 21:44:43.0
mina框架接收数据包连在一块问题。
我最近用java Mina框架写了一个服务器程序,在100个连接同时发送数据时候,服务器这边有时候收到的数据包会连在一块,有时候一个包会拆成两次发送,我很郁闷,这样给我进行协议解析造成很大麻烦。请教一下CSDN上面有用过Mina框架的大侠这是怎么回事?

------解决方案--------------------------------------------------------
哦我也只是初步怀疑一下,现在找到官方对于多包并作一包发送的解释:

是OS提高发包效率的做法

Why does SocketConnector send several messages as one message?

For example, I tried using SocketConnector to send "abc" and "def", but it sent "abcdef". Is it a MINA bug?

No, this is due to your OS trying to send packets more efficiently (see http://en.wikipedia.org/wiki/Nagle_algorithm). You can enable/disable Nagle's algorithm by a call to SocketSessionConfig.setTcpNoDelay(), e.g.:

((SocketSessionConfig) connector.getSessionConfig()).setTcpNoDelay(false)

However, even if you do this you cannot expect one session.write(bytes) in MINA to correspond to one TCP packet on your network. You should probably implement your own MINA ProtocolDecoder to handle the assembly of incoming bytes into message objects. The TextLineCodec is a good start if the protocol you're implementing is based on text lines. For a more advanced example have a look at the SumUp example in the MINA distribution.

http://mina.apache.org/faq#FAQ-WhydoesSocketConnectorsendseveralmessagesasonemessage%253F