/** 
 * This program is an example from the book "Internet 
 * programming with Java" by Svetlin Nakov. It is freeware. 
 * For more information: http://www.nakov.com/books/inetjava/ 
 */ 
import java.applet.Applet; 
import java.awt.*; 
import java.net.Socket; 
import java.io.*; 
 
public class StockQuoteApplet extends Applet 
        implements Runnable { 
    public static final int STOCK_SERVER_PORT = 2004; 
    public static final String COMPANY_TICKER = "MSFT"; 
 
    private BufferedReader mSocketReader; 
    private TextArea mTextArea = new TextArea(); 
 
    public void init() { 
        try { 
            // Establish TCP socket connection with the server 
            String host = this.getCodeBase().getHost(); 
            Socket sock = new Socket(host, STOCK_SERVER_PORT); 
 
            // Send the company ticker to the server 
            OutputStreamWriter socketWriter = 
                new OutputStreamWriter(sock.getOutputStream()); 
            socketWriter.write(COMPANY_TICKER + "\n"); 
            socketWriter.flush(); 
 
            // Get the input stream reader 
            mSocketReader = new BufferedReader( 
                new InputStreamReader(sock.getInputStream())); 
        } catch (IOException ioex) { 
            ioex.printStackTrace(); 
            System.exit(-1); 
        } 
 
        // Set the layout manager to null 
        this.setLayout(null); 
 
        // Create the text area and add it to the applet 
        mTextArea.setBounds(new Rectangle(0, 0, 300, 150)); 
        this.add(mTextArea); 
 
        // Create and start socket reader thread 
        Thread sockerReaderThread = new Thread(this); 
        sockerReaderThread.start(); 
    } 
 
    public void run() { 
        try { 
            while (true) { 
                String line = mSocketReader.readLine(); 
                mTextArea.append(line); 
                mTextArea.append("\n"); 
            } 
        } catch (IOException ioex) { 
            ioex.printStackTrace(); 
        } 
    } 
}
Back to Internet Programming with Java books's web site