Table of Contents

advertisement
Java Network
Programming
Solutions to
Exercises
Java Network Programming: Solutions to Exercises
Page i
Table of Contents
Exercise 1: Mapping Names to IP Addresses .................................................................................. 1
Exercise 2: The Finger Application ................................................................................................... 2
Exercise 3: Writing a Finger Server .................................................................................................. 4
Exercise 4: Receiving Stock Quotes................................................................................................. 6
Exercise 5: Displaying a Page from a URL ...................................................................................... 8
Exercise 6: A Chat Server and Client ............................................................................................. 10
Exercise 7: Using Text Streams ..................................................................................................... 13
Exercise 8: Using Serialization ....................................................................................................... 15
Exercise 9: ...................................................................................................................................... 17
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 1
Exercise 1:
Mapping Names to IP 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);
}
}
}
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 2
Exercise 2: 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();
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 3
}
}
// 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);
}
}
}
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 4
Exercise 3: 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);
}
}
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 5
// This method handles reply on one socket to one client.
private void sendReply(Socket socket) {
try {
// 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);
}
}
}
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 6
Exercise 4: Receiving Stock Quotes
package mycode;
import
import
import
import
import
course.application.*;
course.stock.*;
java.io.*;
java.net.*;
java.util.*;
public class StockClientApp extends ApplicationBase {
//================================================
// Static Variables
//================================================
public static final int PORT = 6000;
//================================================
// Instance Variables
//================================================
private DatagramSocket _socket;
//================================================
// Methods for labs:
//================================================
// Initialize socket.
private void openSocket() throws IOException {
_socket = new DatagramSocket();
}
// Send request for stock
private void sendRequest() throws IOException {
String strHost = CommandLine.getSwitchValue("host");
String strStock = CommandLine.getSwitchValue("stock");
// Construct datagram packet with name of stock.
// Send it to specified host, listening on PORT
byte[] btName = strStock.getBytes();
InetAddress addr = InetAddress.getByName(strHost);
DatagramPacket dp =
new DatagramPacket(btName, btName.length, addr, PORT);
_socket.send(dp);
}
public void init() {
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 7
try {
openSocket();
System.out.println("Socket is open");
sendRequest();
System.out.println("Stocks are loaded");
new ReaderThread();
}
catch(IOException e) {
System.err.println("Can't open socket:\n" + e);
System.exit(-1);
}
}
//================================================
// Private Inner Class: ReaderThread
//================================================
private class ReaderThread extends Thread {
public ReaderThread() {
super();
start();
System.out.println("Reader thread started");
}
public void run() {
// Create a single DatagramPacket for receiving
byte[] btData = new byte[100];
DatagramPacket dp =
new DatagramPacket(btData, btData.length);
// Go into loop, keep receiving packets
while( true ) {
// Receive next packet into dp:
try {
_socket.receive(dp);
}
catch(IOException e) {}
// Show the stock.
showStock(dp);
} // End of while()
} // End of run()
private void showStock(DatagramPacket dp) {
// Convert packet to a string and display
String strData = new String(dp.getData(), dp.getOffset(),
dp.getLength());
System.out.println("Received stock data: " + strData);
}
}
}
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 8
Exercise 5: 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"));
}
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 9
}
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 10
Exercise 6: A Chat Server
and Client
Chatter.java
package mycode;
import course.rmi.*;
import java.rmi.*;
public interface Chatter extends Remote {
public void sendMessage( String msg ) throws RemoteException;
}
ChatterImpl.java
package mycode;
import course.rmi.*;
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class ChatterImpl extends UnicastRemoteObject
implements Chatter {
private ChatClientGUI _gui;
// This explicit c'tor is necessary because super()
// throws a checked exception.
public ChatterImpl(ChatClientGUI gui) throws RemoteException {
super(); // This causes object to be exported.
_gui = gui;
}
public void sendMessage( String msg ) throws RemoteException {
_gui.appendOutput(msg);
}
}
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 11
ChatClientApp.java
package mycode;
import
import
import
import
course.rmi.*;
course.application.*;
java.io.*;
java.rmi.*;
public class ChatClientApp extends GuiApplicationBase {
//================================================
// Instance Variables
//================================================
private ChatClientGUI _gui;
private ChatRoom
_chatroom;
//================================================
// Methods for labs:
//================================================
//-----------------------------------------------// Join group
//-----------------------------------------------public void join(String strChatterName) {
try {
Chatter c = new ChatterImpl(_gui);
_chatroom.registerChatter(c, strChatterName);
}
catch(Exception e) {
_gui.appendOutput("Couldn't join:\n" + e);
}
}
//-----------------------------------------------// Write list to serialized object
//-----------------------------------------------public void sendMessage(String strMsg) {
try {
_chatroom.broadCast(strMsg);
}
catch(Exception e) {
_gui.appendOutput("Couldn't send message:\n" + e);
}
}
//================================================
// GUI methods
//================================================
// Called after GUI is created.
public void init() {
_gui = (ChatClientGUI) getGui();
// Make sure command line switch was passed in.
if(! CommandLine.isSwitch("ObjectName"))
throw new IllegalArgumentException(
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 12
"\nUse -ObjectName switch to set registered name of ChatRoom
object\n" +
"For example: java ChatClient -ObjectName=lab/ChatRoom\n");
if(! CommandLine.isSwitch("Host"))
throw new IllegalArgumentException(
"\nUse -Host switch to set server host \n" +
"For example: java ChatClient -Host=somedomain.com\n");
// Set security manager because server uses remote clients.
System.setSecurityManager(new RMISecurityManager());
// Now try to connect to object
try {
String strObjName = CommandLine.getSwitchValue("ObjectName");
String strHost
= CommandLine.getSwitchValue("Host");
String strURL = "rmi://" + strHost + "/" + strObjName;
_chatroom = (ChatRoom) Naming.lookup(strURL);
System.out.println("Connected to ChatRoom!");
}
catch(Exception e) {
ApplicationBase.printException("Couldn't bind ChatRoom:", e);
System.exit(-1);
}
}
} // End of ChatClientApp class
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 13
Exercise 7: Using Text Streams
package mycode;
import
import
import
import
course.client.ListClientGUI;
course.util.*;
java.util.Vector;
java.io.*;
public class ListClientApp {
private ListClientGUI _gui;
//-----------------------------------------------// Read input to list from text file
//-----------------------------------------------public Vector readTextFile(String strFileName) {
try {
Vector v = new Vector();
FileReader fr = new FileReader(strFileName);
BufferedReader br = new BufferedReader(fr);
String strLine = br.readLine();
while(strLine != null) {
v.addElement(strLine);
strLine = br.readLine();
}
br.close();
return v;
}
catch(Exception e) {
System.out.println("Exception in readTextFile():\n" + e);
return null;
}
}
//-----------------------------------------------// Write list to a text file
//-----------------------------------------------public void writeTextFile(String strFileName, Vector v) {
try {
FileWriter fr = new FileWriter(strFileName);
PrintWriter pr = new PrintWriter(fr);
for( int i = 0; i < v.size(); i++ ) {
pr.println(v.elementAt(i));
}
pr.close();
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 14
}
catch(Exception e) {
System.out.println("Exception in writeTextFile():\n" + e);
}
}
//-----------------------------------------------// Read input to list from file containing
// serialized Vector
//-----------------------------------------------public Vector readObjectFile(String strFileName) {
return null;
}
//-----------------------------------------------// Write list to serialized object
//-----------------------------------------------public void writeObjectFile(String strFileName, Vector v) {
return;
}
// Called after GUI is created.
public void init() {
Vector v = null;
if( CommandLine.isSwitch("InputText") )
v = readTextFile(CommandLine.getSwitchValue("InputText"));
else if( CommandLine.isSwitch("InputObject") )
v = readObjectFile(CommandLine.getSwitchValue("InputObject"));
_gui.setList(v);
}
public void quit(Vector v) {
if( CommandLine.isSwitch("OutputText") )
writeTextFile(CommandLine.getSwitchValue("OutputText"), v);
else if( CommandLine.isSwitch("OutputObject") )
writeObjectFile(CommandLine.getSwitchValue("OutputObject"), v);
System.exit(0);
}
// Assign GUI to this App
public void setGui( ListClientGUI gui ) {
if( _gui == null ) {
// Assign only once
_gui = gui;
init();
}
}
} // End of ListClientApp class
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 15
Exercise 8:
Using Serialization
package mycode;
import
import
import
import
course.client.ListClientGUI;
course.util.*;
java.util.Vector;
java.io.*;
public class ListClientApp {
private ListClientGUI _gui;
-------------------------------------------------------//-----------------------------------------------// Read input to list from file containing
// serialized Vector
//-----------------------------------------------public Vector readObjectFile(String strFileName) {
try {
Vector v = new Vector();
FileInputStream fis = new FileInputStream(strFileName);
ObjectInputStream oos = new ObjectInputStream(fis);
v = (Vector) oos.readObject();
oos.close();
return v;
}
catch(Exception e) {
System.out.println("Exception in readObjectFile():\n" + e);
return null;
}
}
//-----------------------------------------------// Write list to serialized object
//-----------------------------------------------public void writeObjectFile(String strFileName, Vector v) {
try {
FileOutputStream fos = new FileOutputStream(strFileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(v);
oos.close();
}
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 16
catch(Exception e) {
System.out.println("Exception in writeObjectFile():\n" + e);
}
}
-------------------------------------------------------} // End of ListClientApp class
© 2000 SkillBuilders, Inc.
V 2.0
Java Network Programming: Solutions to Exercises
Page 17
Exercise 9:
© 2000 SkillBuilders, Inc.
V 2.0
Download