01: // $Id: NBMessageForm_NIO.java,v 1.3 2005/06/30 15:38:43 belaban Exp $
02:
03: package org.jgroups.blocks;
04:
05: import java.io.IOException;
06: import java.nio.ByteBuffer;
07: import java.nio.channels.SocketChannel;
08:
09: /**
10: * NBMessageForm - Message form for non-blocking message reads.
11: * @author akbollu
12: * @author Bela Ban
13: */
14: public class NBMessageForm_NIO {
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 NBMessageForm_NIO(int dataBuffSize, SocketChannel ch) {
24: headerBuffer = ByteBuffer.allocate(HEADER_SIZE);
25: dataBuffer = ByteBuffer.allocate(dataBuffSize);
26: channel = ch;
27: }
28:
29: public ByteBuffer readCompleteMsgBuffer() throws IOException {
30:
31: int rt;
32:
33: try {
34: rt = channel.read(headerBuffer);
35: if ((rt == 0) || (rt == -1)) {
36: channel.close();
37: return null;
38: }
39: if (rt == HEADER_SIZE) {
40: headerBuffer.flip();
41: messageSize = headerBuffer.getInt();
42: if (dataBuffer.capacity() < messageSize) {
43: dataBuffer = ByteBuffer.allocate(messageSize);
44: }
45: } else {
46: return null;
47: }
48: } catch (IOException ex) {
49: channel.close();
50: throw ex;
51: }
52:
53: //rt == 0 need not be checked twice in the same event
54: channel.read(dataBuffer);
55: if (isComplete()) {
56: dataBuffer.flip();
57: return dataBuffer;
58: }
59: return null;
60: }
61:
62: public void reset() {
63: dataBuffer.clear();
64: headerBuffer.clear();
65: messageSize = 0;
66: w_in_p = false;
67: }
68:
69: private boolean isComplete() {
70: return (dataBuffer.position() == messageSize);
71: }
72: }
|