KickJava   Java API By Example, From Geeks To Geeks.

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


1 // $Id: NBMessageForm_NIO.java,v 1.3 2005/06/30 15:38:43 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  * @author Bela Ban
13  */

14 public class NBMessageForm_NIO
15 {
16     ByteBuffer JavaDoc headerBuffer = null;
17     ByteBuffer JavaDoc 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 JavaDoc channel = null;
23
24
25
26     public NBMessageForm_NIO(int dataBuffSize, SocketChannel JavaDoc ch)
27     {
28         headerBuffer = ByteBuffer.allocate(HEADER_SIZE);
29         dataBuffer = ByteBuffer.allocate(dataBuffSize);
30         channel = ch;
31     }
32
33
34
35     public ByteBuffer JavaDoc readCompleteMsgBuffer() throws IOException JavaDoc
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 JavaDoc ex) {
61             channel.close();
62             throw ex;
63         }
64
65
66         //rt == 0 need not be checked twice in the same event
67
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