开发者

Partial message problem using java nio

开发者 https://www.devze.com 2023-03-08 14:50 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号