Partial message problem using java nio
My sending messages may be large开发者_如何学运维r than the default socket buffer size. So there may be several read operations in order to receive a complete message. When the end condition is
n = socket.read(rbuf);
if(n==0) || (n==-1)
break;
The exception of partial message still exists. Is any good way to solve this problem. Thanks
I use multiple processes running on one machine. Each process uses a nio socket. Is this a possible factor to cause the partial messages?
0 is a valid return value for read, which does not indicate the end of the channel. -1 indicates the end of the channel. So if you end the reading when 0 is returned, you'll get partial messages.
I would suggest using Netty which is built on top of Java's NIO classes but gives you a (in my opinion) much more usable API than the Java JDK NIO classes.
To solve your problem you would use a ReplayingDecoder and Netty will simply call your stream (ChannelBuffer) decoder again and again until you've got enough data to make sense of it.
精彩评论