FileDocCategorySizeDatePackage
AsyncReadSocket.javaAPI DocExample1385Tue Jan 28 17:11:58 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 2, p. 26.  This example contains a bug
// (described in chapter 2) -- see the AsyncReadSocket for chapter 3.

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

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();
                result.append(c);
            } catch (Exception e) {}
        }
    }

    // Get the string already read from the socket so far.
    // This method is used by the Applet thread to obtain the data
    //  in a synchronous manner.
    public String getResult() {
        String retval = result.toString();
        result = new StringBuffer();
        return retval;
    }
}