You are on page 1of 24

Advanced Java

Core Techniques

Solutions to
Workshops
Advanced Java Core Techniques: Solutions to Workshops Page i

Table of Contents

Lesson 1: Using Basic Threads........................................................................................................1


Lesson 2: Thread States ..................................................................................................................6
Lesson 5: Using Text Streams .......................................................................................................11
Lesson 6: Serialization ..................................................................................................................14
Lesson 8: Inet Addresses ...............................................................................................................16
Lesson 9: The Finger Application...................................................................................................17
Lesson 10: Writing a Finger Server................................................................................................19
Lesson 11: Displaying a Page from a URL ...................................................................................21

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 1

Lesson 1:
Using Basic Threads

// StockApp.java

// Threads Basics Workshop

import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;

// StockStream class
class StockStream extends Thread {
private Stock _stock;
private List _lstOutput;

public StockStream(Stock stock, List lstOutput) {


super(stock.getName()); // Use stock name as thread name
_stock = stock;
_lstOutput = lstOutput;
}

public void run() {


boolean _bContinue = true;
while (_bContinue) {
String s = _stock.getName() + ": " + _stock.getPriceAsString();
_lstOutput.add(s);
_lstOutput.makeVisible(_lstOutput.getItemCount() - 1);
try {
// Sleep for a random interval
// between 500 and 1000 milliseconds
Thread.sleep((int) (Math.random() * 500) + 500);
}
catch (InterruptedException e) {
_bContinue = false;
}
}
}
} // End of StockStream class

// Stock class encapsulates a single stock


class Stock {
private String _name;
private double _low, _high;

// Basic c'tor for setting attributes


public Stock(String name, double low, double high) {

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 2

_name = name;
_low = low;
_high = high;
}

// Basic getters for attributes


public String getName() {
return _name;
}
public double getLow() {
return _low;
}
public double getHigh() {
return _high;
}

public double getPrice() {


// Get a random price between low and high
return _low + (Math.random() * (_high - _low));
}

public String getPriceAsString() {


String s = "" + getPrice();
return s.substring(0, s.indexOf('.') + 3);
}

public String toString() {


return getName() + ": " + getLow() + " / " + getHigh();
}
}

class StockAppGui extends Frame implements Runnable {


private String[] _args;
private List _lstPrices = new List();
private List _lstStocks = new List();
private TextField _tfName = new TextField();
private TextField _tfLow = new TextField();
private TextField _tfHigh = new TextField();
private ButtonHandler _btnh = new ButtonHandler();
private Hashtable _htStocks = new Hashtable();
private Vector _vThreads = new Vector();
private Thread _thrAuto;
StockStream ss;

public StockAppGui(String[] args) {


super("Stock Feed Application");
_args = args;
initLayout();

// Add a few stocks just for convenience:


addStock("IBM", "70.4", "90.4");
addStock("ATT", "40.1", "49.4");
addStock("NSC", "99.2", "125.7");

show();
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 3

// APP METHODS
private void addStock(String sName, String sLow, String sHigh) {
// Instantiate Stock with values from TextFields
double low = Double.valueOf(sLow).doubleValue();
double high = Double.valueOf(sHigh).doubleValue();
Stock stk = new Stock(sName, low, high);

_htStocks.put(sName, stk); // Add to hashtable


_lstStocks.add(stk.toString()); // Add to list

// Clear text fields


_tfName.setText("");
_tfLow.setText("");
_tfHigh.setText("");
_tfName.requestFocus();
}

private void startStream() {


// Go through Hashtable of stocks, create a thread for
// each in the Vector.
Enumeration e = _htStocks.elements();
while (e.hasMoreElements()) {
Stock stk = (Stock) e.nextElement();
StockStream ss = new StockStream(stk, _lstPrices);
ss.start();
_vThreads.add(ss);
}
}

private void stopStream() {


// Go through Vector of threads, stop each one.
// Then clear Vector.
Enumeration e = _vThreads.elements();
while (e.hasMoreElements())
/////////////// here
// ((StockStream) e.nextElement()).stop();
//_bContinue = false;
((StockStream) e.nextElement()).interrupt();
_vThreads.clear();
}

private void startAutoRun() {


_thrAuto = new Thread(this);
_thrAuto.start();
}

private void stopAutoRun() {


}

private void toggleAutoRun() {


startAutoRun();
}

// run() method for master thread


public void run() {
// Start the stream, pause 5 seconds, stop stream
startStream();
try {

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 4

Thread.sleep(5000);
} catch (InterruptedException e) {
}

stopStream();
}

// SETUP METHODS

private void initLayout() {


Panel pnlMain = new Panel();
pnlMain.setLayout(new GridLayout(1, 2));
pnlMain.add(getStockFeedPanel());
pnlMain.add(getStockPanel());

add(BorderLayout.CENTER, pnlMain); // Add main panel to frame


setBounds(100, 100, 400, 300);

// Add WindowListener to close window


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

private Panel getStockFeedPanel() {


Panel pnl = new Panel();
pnl.setLayout(new BorderLayout());
pnl.add(BorderLayout.CENTER, _lstPrices);
pnl.add(BorderLayout.SOUTH, getStockFeedButtonPanel());
return pnl;
}

private Panel getStockFeedButtonPanel() {


Panel pnl = new Panel();
Button btn[] = new Button[3];
btn[0] = new Button("Start");
btn[1] = new Button("Auto");
btn[2] = new Button("Clear");
for (int i = 0; i < btn.length; i++) {
btn[i].setActionCommand(btn[i].getLabel().toLowerCase());
btn[i].addActionListener(_btnh);
pnl.add(btn[i]);
}
return pnl;
}

private Panel getStockPanel() {


Panel pnl = new Panel();
pnl.setLayout(new GridLayout(2, 1));
pnl.add(_lstStocks);
pnl.add(getStockEntryPanel());
return pnl;
}

private Panel getStockEntryPanel() {

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 5

// Set up panel
Panel pnlMain = new Panel();
pnlMain.setLayout(new BorderLayout());

Panel pnlCenter = new Panel();


pnlCenter.setLayout(new GridLayout(3, 2));
pnlCenter.add(new Label("Name:", Label.RIGHT));
pnlCenter.add(_tfName);
pnlCenter.add(new Label("Low:", Label.RIGHT));
pnlCenter.add(_tfLow);
pnlCenter.add(new Label("High:", Label.RIGHT));
pnlCenter.add(_tfHigh);
pnlMain.add(BorderLayout.CENTER, pnlCenter);

Panel pnlSouth = new Panel();


Button btnAdd = new Button("Add");
btnAdd.setActionCommand(btnAdd.getLabel().toLowerCase());
btnAdd.addActionListener(_btnh);
pnlSouth.add(btnAdd);
pnlMain.add(BorderLayout.SOUTH, pnlSouth);

return pnlMain;
}

// INNER CLASSES
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
Button btn = (Button) ae.getSource();
if (ae.getActionCommand().equals("start")) {
startStream();
btn.setLabel("Stop");
btn.setActionCommand("stop");
} else if (ae.getActionCommand().equals("stop")) {
stopStream();
btn.setLabel("Start");
btn.setActionCommand("start");
} else if (ae.getActionCommand().equals("clear")) {
_lstPrices.removeAll();
} else if (ae.getActionCommand().equals("add")) {
addStock(
_tfName.getText(),
_tfLow.getText(),
_tfHigh.getText());
} else if (ae.getActionCommand().equals("auto")) {
toggleAutoRun();
}
}
} // End of inner class ButtonHandler
} // End of StockAppGui class

class StockApp {
public static void main(String[] args) {
new StockAppGui(args);
}
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 6

Lesson 2:
Thread States

// StockApp.java

// Threads Lab 2.

import java.awt.*;
import java.awt.event.*;
import java.util.Hashtable;
import java.util.Vector;
import java.util.Enumeration;
// StockStream class
class StockStream extends Thread {
private Stock _stock;
private List _lstOutput;

public StockStream( Stock stock, List lstOutput ) {


super( stock.getName() ); // Use stock name as thread name
_stock = stock;
_lstOutput = lstOutput;
}
public void run() {
boolean _bContinue = true;
while (_bContinue) {
String s = _stock.getName() + ": " + _stock.getPriceAsString();
_lstOutput.add(s);
_lstOutput.makeVisible(_lstOutput.getItemCount() - 1);
try {
// Sleep for a random interval
// between 500 and 1000 milliseconds
Thread.sleep((int) (Math.random() * 500) + 500);
}
catch( InterruptedException e ) {
_bContinue = false;
}
}
}
} // End of StockStream class

// Stock class encapsulates a single stock


class Stock {
private String _name;
private double _low, _high;

// Basic c'tor for setting attributes


public Stock( String name, double low, double high ) {
_name = name;
_low = low;
_high = high;
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 7

// Basic getters for attributes


public String getName() {
return _name;
}
public double getLow() {
return _low;
}
public double getHigh() {
return _high;
}
public double getPrice() {
// Get a random price between low and high
return _low + (Math.random() * (_high - _low));
}
public String getPriceAsString() {
String s = "" + getPrice();
return s.substring(0, s.indexOf('.') + 3);
}
public String toString() {
return getName() + ": " + getLow() + " / " + getHigh();
}
}

class StockAppGui extends Frame implements Runnable {


private String[] _args;
private List _lstPrices = new List();
private List _lstStocks = new List();
private TextField _tfName = new TextField();
private TextField _tfLow = new TextField();
private TextField _tfHigh = new TextField();
private ButtonHandler _btnh = new ButtonHandler();
private Hashtable _htStocks = new Hashtable();
private Vector _vThreads = new Vector();
private Thread _thrAuto;

public StockAppGui( String[] args ) {


super( "Stock Feed Application" );
_args = args;
initLayout();
// Add a few stocks just for convenience:
addStock( "IBM", "70.4", "90.4" );
addStock( "ATT", "40.1", "49.4" );
addStock( "NSC", "99.2", "125.7" );

show();
}

// APP METHODS
private void addStock(String sName, String sLow, String sHigh) {
// Instantiate Stock with values from TextFields
double low = Double.valueOf( sLow ).doubleValue();
double high = Double.valueOf( sHigh ).doubleValue();
Stock stk = new Stock( sName, low, high );

_htStocks.put( sName, stk ); // Add to hashtable


_lstStocks.add( stk.toString() ); // Add to list

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 8

// Clear text fields


_tfName.setText("");
_tfLow. setText("");
_tfHigh.setText("");
_tfName.requestFocus();
}
private void startStream() {
// Go through Hashtable of stocks, create a thread for
// each in the Vector.
Enumeration e = _htStocks.elements();
while( e.hasMoreElements() ) {
Stock stk = (Stock) e.nextElement();
StockStream ss = new StockStream( stk, _lstPrices );

System.out.println("StockStream for " + ss.getName() +


" before start(): isAlive() returns " + ss.isAlive());
ss.start();

System.out.println("StockStream for " + ss.getName() +


" after start(): isAlive() returns " + ss.isAlive());

_vThreads.addElement( ss );
}
}
private void stopStream() {
// Go through Vector of threads, stop each one.
// Then clear Vector.
Enumeration e = _vThreads.elements();
while (e.hasMoreElements())

((StockStream) e.nextElement()).interrupt();
System.out.println("StockStream stopped");

_vThreads.clear();
}

private void startAutoRun() {


_thrAuto = new Thread(this);
_thrAuto.start();
}
private void stopAutoRun() {
_thrAuto.interrupt();
}
// run() method for master thread
public void run() {
// Start the stream, pause 20 seconds, stop stream
startStream();
try {
Thread.sleep(20000);
}
catch( InterruptedException e ) {
System.out.println("Auto thread interrupted");
}
stopStream();
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 9

// SETUP METHODS

private void initLayout() {


Panel pnlMain = new Panel();
pnlMain.setLayout( new GridLayout(1,2) );
pnlMain.add( getStockFeedPanel() );
pnlMain.add( getStockPanel() );

add( BorderLayout.CENTER, pnlMain ); // Add main panel to frame


setBounds( 100, 100, 400, 300 );

// Add WindowListener to close window


addWindowListener( new WindowAdapter() {
public void windowClosing( WindowEvent we ) {
System.exit(0);
}
} );

}
private Panel getStockFeedPanel() {
Panel pnl = new Panel();
pnl.setLayout( new BorderLayout() );
pnl.add( BorderLayout.CENTER, _lstPrices );
pnl.add( BorderLayout.SOUTH, getStockFeedButtonPanel() );
return pnl;
}

private Panel getStockFeedButtonPanel() {


Panel pnl = new Panel();
Button btn[] = new Button[3];
btn[0] = new Button("Start");
btn[1] = new Button("Auto");
btn[2] = new Button("Clear");
for( int i = 0; i < btn.length; i++ ) {
btn[i].setActionCommand(btn[i].getLabel().toLowerCase());
btn[i].addActionListener( _btnh );
pnl.add(btn[i]);
}
return pnl;
}

private Panel getStockPanel() {


Panel pnl = new Panel();
pnl.setLayout( new GridLayout(2,1) );
pnl.add( _lstStocks );
pnl.add( getStockEntryPanel() );
return pnl;
}

private Panel getStockEntryPanel() {


// Set up panel
Panel pnlMain = new Panel();
pnlMain.setLayout( new BorderLayout() );

Panel pnlCenter = new Panel();


pnlCenter.setLayout( new GridLayout(3,2) );
pnlCenter.add(new Label("Name:", Label.RIGHT));
pnlCenter.add(_tfName);

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 10

pnlCenter.add(new Label("Low:", Label.RIGHT));


pnlCenter.add(_tfLow);
pnlCenter.add(new Label("High:", Label.RIGHT));
pnlCenter.add(_tfHigh);
pnlMain.add( BorderLayout.CENTER, pnlCenter );

Panel pnlSouth = new Panel();


Button btnAdd = new Button("Add");
btnAdd.setActionCommand(btnAdd.getLabel().toLowerCase());
btnAdd.addActionListener( _btnh );
pnlSouth.add(btnAdd);
pnlMain.add( BorderLayout.SOUTH, pnlSouth );

return pnlMain;
}

// INNER CLASSES
private class ButtonHandler implements ActionListener {
public void actionPerformed( ActionEvent ae ) {
Button btn = (Button) ae.getSource();
if( ae.getActionCommand().equals("start")) {
startStream();
btn.setLabel("Stop");
btn.setActionCommand("stop");
}
else if( ae.getActionCommand().equals("stop")) {
stopStream();
btn.setLabel("Start");
btn.setActionCommand("start");
}
else if( ae.getActionCommand().equals("clear")) {
_lstPrices.removeAll();
}
else if( ae.getActionCommand().equals("add")) {
addStock( _tfName.getText(), _tfLow.getText(),
_tfHigh.getText() );
}
else if( ae.getActionCommand().equals("auto")) {
if( _thrAuto != null && _thrAuto.isAlive() )
stopAutoRun();
else
startAutoRun();
}
}
} // End of inner class ButtonHandler
} // End of StockAppGui class

class StockApp {
public static void main( String[] args ) {
new StockAppGui(args);
}
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 11

Lesson 5:
Using Text Streams

package mycode;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import java.util.Vector;
import java.util.Iterator;

public class TextFileReaderWriter {

public static void main(String[] args) {


String inputFileName;
String outputFileName;
String serializedObjectName;
Vector vec;

TextFileReaderWriter tfrw = new TextFileReaderWriter();

if (args.length < 1) {
tfrw.info(
"{Input File Name}
[{output File Name}] [{name of serialized vector}]");
return;
}
inputFileName = args[0];

tfrw.info("Reading file: " + inputFileName);

vec = tfrw.readTextFile(inputFileName);

if (vec == null) {
return;
}

tfrw.info("Read " + vec.size() + " lines from input file");

if (args.length < 2 || args[1].length() == 0) {


tfrw.printLines(vec);
} else {
outputFileName = args[1];
tfrw.info("Writing file " + outputFileName);
tfrw.writeTextFile(outputFileName, vec);
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 12

if (args.length == 3 && args[2].length() != 0) {


serializedObjectName = args[2];
tfrw.info("Serializing vector to file " + serializedObjectName);
tfrw.serializeVector(serializedObjectName, vec);
}
}

//------------------------------------------------
// Read input from text file
//------------------------------------------------
public Vector readTextFile(String inputFileName) {
try {
Vector vec = new Vector();
FileReader fr = new FileReader(inputFileName);
BufferedReader br = new BufferedReader(fr);

String strLine = br.readLine();

while (strLine != null) {


vec.add(strLine);
strLine = br.readLine();
}
br.close();
return vec;
} catch (Exception e) {
info("Exception in readTextFile():");
info(e.getClass().getName());
info(e.getMessage());
return null;
}
}

//------------------------------------------------
// Print to standard output
//------------------------------------------------
public void printLines(Vector vec) {
Iterator iter = vec.iterator();

while (iter.hasNext()) {
System.out.println((String) iter.next());
}
}

//------------------------------------------------
// Write to a text file
//------------------------------------------------
public void writeTextFile(String outputFileName, Vector vec) {
try {
FileWriter fw = new FileWriter(outputFileName);
PrintWriter pw = new PrintWriter(fw);
Iterator iter = vec.iterator();
while (iter.hasNext()) {
pw.println((String) iter.next());
}
pw.close();
} catch (Exception e) {
info("Exception in writeTextFile():");
info(e.getClass().getName());

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 13

info(e.getMessage());
}
}
//------------------------------------------------
// Serialize the vector
//------------------------------------------------
public void serializeVector(String fileName, Vector vec) {
try {
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(vec);
oos.close();
} catch (Exception e) {
info("Exception in writeObjectFile():");
info(e.getClass().getName());
info(e.getMessage());
}
}

public void info(Object o) {


System.err.println(getClass().getName() + " " + o.toString());
}
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 14

Lesson 6: Serialization

package mycode;

import java.io.FileInputStream;
import java.io.ObjectInputStream;

import java.util.Vector;
import java.util.Iterator;

public class SerializedObjectReader {

public static void main(String[] args) {


String serializedObjectName;
Vector vec;

SerializedObjectReader sor = new SerializedObjectReader();

if (args.length < 1) {
sor.info(
"{name of serialized vector} [-print]");
return;
}
serializedObjectName = args[0];

sor.info("Deserializing " + serializedObjectName);

vec = sor.readObjectFile(serializedObjectName);

if (vec == null) {
return;
}

if (args.length == 2 && args[1].equals("-print")) {


sor.info("Lines in deserialized vector: " + vec.size());
}

sor.printLines(vec);
}

//------------------------------------------------
// Print to standard output
//------------------------------------------------
public void printLines(Vector vec) {
Iterator iter = vec.iterator();

while (iter.hasNext()) {
System.out.println((String) iter.next());
}
}

// ------------------------------------------------

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 15

// Read serialized object (in this case a Vector)


// and reconstitute it in a Vector object
//------------------------------------------------
public Vector readObjectFile(String strFileName) {
try {
Vector vec;

FileInputStream fis = new FileInputStream(strFileName);


ObjectInputStream oos = new ObjectInputStream(fis);
vec = (Vector) oos.readObject();
oos.close();
return vec;
} catch (Exception e) {
info("Exception in readObjectFile():");
info(e.getClass().getName());
info(e.getMessage());
return null;
}
}

public void info(Object o) {


System.err.println(getClass().getName() + " " + o.toString());
}
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 16

Lesson 8:
Inet Addresses

import java.io.*;
import java.net.*;
import course.application.Keyboard;

public class IPLookup {

// This method is called by main() to display all addresses


// of specified host.
private static void displayHost(String strHost) {
try {
InetAddress addr[] = InetAddress.getAllByName(strHost);
for (int i = 0; i < addr.length; i++) {
System.out.println("The IP address is " + addr[i].toString());
}
}
catch (UnknownHostException uhe) {
System.out.println("There is no IP address for " + strHost);
}
System.out.println(); // Blank line
}

public static void main(String args[]) {

try {
Keyboard.setPrompt("Enter a host name or address: > ");
String strInput = Keyboard.getLine();
while( strInput.length() > 0 ) {
displayHost(strInput);
strInput = Keyboard.getLine();
}
}
catch(IOException e) {
System.out.println("Couldn't get keyboard input:\n" + e);
}
}
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 17

Lesson 9:
The Finger Application

package mycode;

import course.application.*;

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

public class FingerClientApp extends ApplicationBase {

//================================================
// Static Variables
//================================================
public static final int fingerPort = 79;

//================================================
// Instance Variables
//================================================
private Socket _socket;
private BufferedReader _br;
private PrintWriter _pw;

private String[] args = CommandLine.getCommandLine();

//================================================
// Methods for labs:
//================================================

// Initialize socket and two stream objects.


private void openSocket(String strHost) throws IOException {
System.err.println("Trying to connect to " + strHost);
_socket = new Socket(strHost, fingerPort);
_pw = new PrintWriter(_socket.getOutputStream());
_br = new BufferedReader(
new InputStreamReader(_socket.getInputStream()));
System.err.println("Connected...");
}

// Write all command line arguments, starting with #1,


// to the output stream. Then flush the stream.
private void sendData() throws IOException {
System.err.println("About to send data to server...");
for (int i = 1; i < args.length; i++) {
_pw.println(args[i]);
_pw.flush();
}
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 18

// Read and display all data from the server.


private void receiveReply() throws IOException {
System.err.println("About to read data from server...");
String str;
while ((str = _br.readLine()) != null)
System.out.println(str);
}

public void init() {


try {
if(args.length > 0)
openSocket(args[0]);
else
openSocket("localhost");

sendData();
receiveReply();
}
catch (IOException e) {
System.err.println(e);
System.exit(0);
}
}
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 19

Lesson 10:
Writing a Finger Server

package mycode;

import course.application.*;
import java.util.Date;

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

public class FingerServerApp extends ApplicationBase {


//================================================
// Static Variables
//================================================
public static final int fingerPort = 79;

//================================================
// Methods for labs:
//================================================
//------------------------------------------------
// Initialize server socket
//------------------------------------------------
public void init() {
ServerSocket srvSocket;
try {

// Initialize server socket here:


srvSocket = new ServerSocket(fingerPort);
System.out.println("FingerServer is ready...");

while (true) {
System.err.println("=======================");
// Receive call from next client:
Socket socket = srvSocket.accept();
System.err.println("Socket accepted from " +
socket.getInetAddress().getHostName());
// Pass new socket to sendReply() method
sendReply(socket);
}
}
catch (IOException e) {
System.err.println(e);
System.exit(0);
}
}

// This method handles reply on one socket to one client.


private void sendReply(Socket socket) {
try {

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 20

// Set timeout to 1 second


socket.setSoTimeout(1000); // Wait only 1 second for data.

// Open streams to/from socket:


BufferedReader br =
new BufferedReader(new
InputStreamReader(socket.getInputStream()));
PrintWriter pw = new PrintWriter(socket.getOutputStream());

System.out.println("Composing reply...");
pw.println(new Date());
pw.println("Reply from Finger server on " +
socket.getLocalAddress().getHostName());

// Echo client's data back.


try {
System.out.println("About to echo client's data back");
String strLine = null;
int iCounter = 0;
while ((strLine = br.readLine()) != null) {
System.out.println(" " + strLine);
pw.println(++iCounter + ": " + strLine);
}
}
catch(InterruptedIOException e) {
// Do nothing; just timed out.
}

pw.flush();
socket.close();
}
catch(IOException e) {
System.err.println("IOException from individual socket:\n" + e);
}
}
}

© 2003 SkillBuilders, Inc. V 2.0


Advanced Java Core Techniques: Solutions to Workshops Page 21

Lesson 11:
Displaying a Page
from a URL

package mycode;

import course.application.*;

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

public class DisplayPageApp extends ApplicationBase {

private void displayPage(String strURL) {


URL url = null;

try {
url = new URL(strURL);
}
catch (MalformedURLException mue) {
System.err.println("Bad URL:\n" + mue);
System.exit(-1);
return;
}

// Now read the data line by line.


try {
InputStreamReader isr =
new InputStreamReader(url.openStream());
BufferedReader br = new BufferedReader(isr);
String strLine;
while ((strLine = br.readLine()) != null) {
System.out.println(strLine);
}
br.close();
}
catch (IOException ioe){}
}

public void init() {


if(! CommandLine.isSwitch("URL")) {
String strMsg = "Use -URL switch to indicate URL";
throw new IllegalArgumentException(strMsg);
}
displayPage(CommandLine.getSwitchValue("URL"));
}
}

© 2003 SkillBuilders, Inc. V 2.0

You might also like