1 3 package org.jgroups.blocks; 4 5 import java.io.IOException ; 6 import java.nio.ByteBuffer ; 7 import java.nio.channels.SocketChannel ; 8 9 13 public class NBMessageForm1_4 14 { 15 ByteBuffer headerBuffer = null; 16 ByteBuffer dataBuffer = null; 17 static final int HEADER_SIZE = 4; 18 final boolean isComplete = false; 19 int messageSize = 0; 20 boolean w_in_p = false; 21 SocketChannel channel = null; 22 23 public NBMessageForm1_4(int dataBuffSize, SocketChannel ch) 24 { 25 headerBuffer = ByteBuffer.allocate(HEADER_SIZE); 26 dataBuffer = ByteBuffer.allocate(dataBuffSize); 27 channel = ch; 28 } 29 30 public ByteBuffer readCompleteMsgBuffer() throws IOException 31 { 32 if (!w_in_p) 33 { 34 int rt = channel.read(headerBuffer); 35 if ( (rt == 0) || (rt == -1) ) 36 { 37 channel.close(); 38 return null; 39 } 40 if (rt == HEADER_SIZE) 41 { 42 headerBuffer.flip(); 43 messageSize = headerBuffer.getInt(); 44 if(dataBuffer.capacity() < messageSize) 45 { 46 dataBuffer = ByteBuffer.allocate(messageSize); 47 } 48 w_in_p = true; 49 } 50 } 51 else 52 { 53 channel.read(dataBuffer); 55 if(isComplete()) 56 { 57 dataBuffer.flip(); 58 return dataBuffer; 59 } 60 } 61 return null; 62 } 63 64 public void reset() 65 { 66 dataBuffer.clear(); 67 headerBuffer.clear(); 68 messageSize = 0; 69 w_in_p = false; 70 } 71 72 private boolean isComplete() 73 { 74 return ( dataBuffer.position() == messageSize ); 75 } 76 } 77 | Popular Tags |