@@ -112,6 +112,7 @@ public Client(PApplet parent, String host, int port) {
112112 }
113113 }
114114
115+
115116 /**
116117 * @param socket any object of type Socket
117118 * @throws IOException
@@ -183,35 +184,49 @@ public void dispose() {
183184 public void run () {
184185 while (Thread .currentThread () == thread ) {
185186 try {
186- while ((input != null ) &&
187- (input .available () > 0 )) { // this will block
187+ while (input != null ) {
188+ int value ;
189+
190+ // try to read a byte using a blocking read.
191+ // An exception will occur when the sketch is exits.
192+ try {
193+ value = input .read ();
194+ } catch (SocketException e ) {
195+ System .err .println ("Client SocketException: " + e .getMessage ());
196+ // the socket had a problem reading so don't try to read from it again.
197+ stop ();
198+ return ;
199+ }
200+
201+ // read returns -1 if end-of-stream occurs (for example if the host disappears)
202+ if (value == -1 ) {
203+ System .err .println ("Client got end-of-stream." );
204+ stop ();
205+ return ;
206+ }
207+
188208 synchronized (buffer ) {
209+ // todo: at some point buffer should stop increasing in size,
210+ // otherwise it could use up all the memory.
189211 if (bufferLast == buffer .length ) {
190212 byte temp [] = new byte [bufferLast << 1 ];
191213 System .arraycopy (buffer , 0 , temp , 0 , bufferLast );
192214 buffer = temp ;
193215 }
194- buffer [bufferLast ++] = (byte ) input . read () ;
216+ buffer [bufferLast ++] = (byte )value ;
195217 }
196- }
197- // now post an event
198- if (clientEventMethod != null ) {
199- try {
200- clientEventMethod .invoke (parent , new Object [] { this });
201- } catch (Exception e ) {
202- System .err .println ("error, disabling clientEvent() for " + host );
203- e .printStackTrace ();
204- clientEventMethod = null ;
218+
219+ // now post an event
220+ if (clientEventMethod != null ) {
221+ try {
222+ clientEventMethod .invoke (parent , new Object [] { this });
223+ } catch (Exception e ) {
224+ System .err .println ("error, disabling clientEvent() for " + host );
225+ e .printStackTrace ();
226+ clientEventMethod = null ;
227+ }
205228 }
206229 }
207-
208- try {
209- // uhh.. not sure what's best here.. since blocking,
210- // do we need to worry about sleeping much? or is this
211- // gonna try to slurp cpu away from the main applet?
212- Thread .sleep (10 );
213- } catch (InterruptedException ex ) { }
214-
215230 } catch (IOException e ) {
216231 //errorMessage("run", e);
217232 e .printStackTrace ();
0 commit comments