Source code: com/iborg/hsocket/HSocketInputStream.java
1 /*
2 * Copyright (C) 2002 iBorg Corporation. All Rights Reserved.
3 * Copyright (C) 2002 Boris Galinsky. All Rights Reserved.
4 *
5 * This file is part of the share system.
6 *
7 * The share system is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation.
10 *
11 * See terms of license at gnu.org.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 */
19
20 /*
21 * HSocketInputStream.java
22 *
23 * Created on March 25, 2002, 1:02 PM
24 */
25
26 package com.iborg.hsocket;
27
28 import java.io.*;
29
30 /**
31 *
32 * @author <a href="mailto:sanych@comcast.net">Boris Galinsky</a>.
33 * @version
34 */
35 public class HSocketInputStream extends InputStream {
36
37 HSocket socket;
38 byte [] data;
39 InputStream dataInputStream;
40
41 /** Creates new HSocketInputStream */
42 public HSocketInputStream(HSocket socket) {
43 this.socket = socket;
44 }
45
46 private void refresh() throws IOException {
47 data = socket.read();
48 dataInputStream = new ByteArrayInputStream(data);
49 }
50
51 public int available() throws IOException {
52 if(dataInputStream == null) {
53 refresh();
54 }
55 int available = 0;
56 if(dataInputStream != null) {
57 available = dataInputStream.available();
58 }
59 return available;
60 }
61
62 public int read() throws java.io.IOException {
63 if(dataInputStream == null) {
64 refresh();
65 }
66 if(dataInputStream != null) {
67 int b = dataInputStream.read();
68 if(b == -1) {
69 dataInputStream = null;
70 return read();
71 } else {
72 return b;
73 }
74 }
75 return -1;
76 }
77
78 public int read(byte[] b, int off, int len) throws java.io.IOException {
79 if(len == 0)
80 return 0;
81
82 if(dataInputStream == null) {
83 refresh();
84 }
85 if(dataInputStream != null) {
86 int r = dataInputStream.read(b, off, len);
87 if(r > 0) {
88 return r;
89 } else {
90 dataInputStream = null;
91 refresh();
92 while(true) {
93 r = dataInputStream.read(b, off, len);
94 if(r > 0) {
95 return r;
96 }
97
98 try {
99 Thread.currentThread().sleep(1000);
100 } catch (Exception e) {
101 }
102 }
103 }
104 }
105 return -1;
106 }
107
108 public boolean markSupported() {
109 return false;
110 }
111 }