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 14 public class NBMessageForm_NIO 15 { 16 ByteBuffer headerBuffer = null; 17 ByteBuffer dataBuffer = null; 18 static final int HEADER_SIZE = 4; 19 final boolean isComplete = false; 20 int messageSize = 0; 21 boolean w_in_p = false; 22 SocketChannel channel = null; 23 24 25 26 public NBMessageForm_NIO(int dataBuffSize, SocketChannel ch) 27 { 28 headerBuffer = ByteBuffer.allocate(HEADER_SIZE); 29 dataBuffer = ByteBuffer.allocate(dataBuffSize); 30 channel = ch; 31 } 32 33 34 35 public ByteBuffer readCompleteMsgBuffer() throws IOException 36 { 37 38 int rt; 39 40 try { 41 rt = channel.read(headerBuffer); 42 if ( (rt == 0) || (rt == -1) ) 43 { 44 channel.close(); 45 return null; 46 } 47 if (rt == HEADER_SIZE) 48 { 49 headerBuffer.flip(); 50 messageSize = headerBuffer.getInt(); 51 if(dataBuffer.capacity() < messageSize) 52 { 53 dataBuffer = ByteBuffer.allocate(messageSize); 54 } 55 } 56 else { 57 return null; 58 } 59 } 60 catch(IOException ex) { 61 channel.close(); 62 throw ex; 63 } 64 65 66 channel.read(dataBuffer); 68 if(isComplete()) 69 { 70 dataBuffer.flip(); 71 return dataBuffer; 72 } 73 return null; 74 } 75 76 77 78 public void reset() 79 { 80 dataBuffer.clear(); 81 headerBuffer.clear(); 82 messageSize = 0; 83 w_in_p = false; 84 } 85 86 private boolean isComplete() 87 { 88 return ( dataBuffer.position() == messageSize ); 89 } 90 } 91 | Popular Tags |