KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > mule > providers > tcp > protocols > LengthProtocol


1 /*
2  * $Id: LengthProtocol.java 3798 2006-11-04 04:07:14Z aperepel $
3  * --------------------------------------------------------------------------------------
4  * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
5  *
6  * The software in this package is published under the terms of the MuleSource MPL
7  * license, a copy of which has been included with this distribution in the
8  * LICENSE.txt file.
9  */

10
11 package org.mule.providers.tcp.protocols;
12
13 import org.mule.providers.tcp.TcpProtocol;
14
15 import java.io.DataInputStream JavaDoc;
16 import java.io.DataOutputStream JavaDoc;
17 import java.io.IOException JavaDoc;
18 import java.io.InputStream JavaDoc;
19 import java.io.OutputStream JavaDoc;
20
21 /**
22  * The LengthProtocol is an application level tcp protocol that can be used to
23  * transfer large amounts of data without risking some data to be loss. The protocol
24  * is defined by sending / reading an integer (the packet length) and then the data
25  * to be transfered.
26  *
27  * @author <a HREF="mailto:gnt@codehaus.org">Guillaume Nodet</a>
28  * @version $Revision: 3798 $
29  */

30 public class LengthProtocol implements TcpProtocol
31 {
32
33     public byte[] read(InputStream JavaDoc is) throws IOException JavaDoc
34     {
35         // Use a mark / reset here so that an exception
36
// will not be thrown is the read times out.
37
// So use the read(byte[]) method that returns 0
38
// if no data can be read and reset the mark.
39
// This is necessary because when no data is available
40
// reading an int would throw a SocketTimeoutException.
41
DataInputStream JavaDoc dis = new DataInputStream JavaDoc(is);
42         byte[] buffer = new byte[32];
43         int length;
44         dis.mark(32);
45         while ((length = dis.read(buffer)) == 0)
46         {
47             // wait
48
}
49         if (length == -1)
50         {
51             return null;
52         }
53         dis.reset();
54         length = dis.readInt();
55         buffer = new byte[length];
56         dis.readFully(buffer);
57         return buffer;
58     }
59
60     public void write(OutputStream JavaDoc os, byte[] data) throws IOException JavaDoc
61     {
62         // Write the length and then the data.
63
DataOutputStream JavaDoc dos = new DataOutputStream JavaDoc(os);
64         dos.writeInt(data.length);
65         dos.write(data);
66         dos.flush();
67     }
68
69 }
70
Popular Tags