FileDocCategorySizeDatePackage
AsyncReadSocket.javaAPI DocExample1305Tue Jan 28 17:12:52 GMT 1997None

AsyncReadSocket.java

// This example is from the book _Java Threads_ by Scott Oaks and Henry Wong. 
// Written by Scott Oaks and Henry Wong.
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.

// Sample AsyncReadSocket -- Chapter 3, p. 49.  This example is fully functional

import java.net.*;
import java.io.*;

public class AsyncReadSocket extends Thread {
     private Socket s;
     private StringBuffer result;

     public AsyncReadSocket(Socket s) {
          this.s = s;
          result = new StringBuffer();
     }

     public void run() {
          DataInputStream is = null;
          try {
               is = new DataInputStream(s.getInputStream());
          } catch (Exception e) {}
          while (true) {
               try {
                    char c = is.readChar();
                    appendResult(c);
               } catch (Exception e) {}
          }
     }

     public synchronized String getResult() {
          String retval = result.toString();
          result = new StringBuffer();
          return retval;
     }

     public synchronized void appendResult(char c) {
          result.append(c)
     }
}