KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jgroups > blocks > NBMessageForm1_4


1 // $Id: NBMessageForm1_4.java,v 1.2 2004/09/23 16:29:11 belaban Exp $
2

3 package org.jgroups.blocks;
4
5 import java.io.IOException JavaDoc;
6 import java.nio.ByteBuffer JavaDoc;
7 import java.nio.channels.SocketChannel JavaDoc;
8
9 /**
10  * NBMessageForm - Message form for non-blocking message reads.
11  * @author akbollu
12  */

13 public class NBMessageForm1_4
14 {
15     ByteBuffer JavaDoc headerBuffer = null;
16     ByteBuffer JavaDoc 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 JavaDoc channel = null;
22     
23     public NBMessageForm1_4(int dataBuffSize, SocketChannel JavaDoc ch)
24     {
25         headerBuffer = ByteBuffer.allocate(HEADER_SIZE);
26         dataBuffer = ByteBuffer.allocate(dataBuffSize);
27         channel = ch;
28     }
29     
30     public ByteBuffer JavaDoc readCompleteMsgBuffer() throws IOException JavaDoc
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             //rt == 0 need not be checked twice in the same event
54
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