Week 6: Basic Java Networking

 

Overview of Networking

 

Networking Basics

Application
(HTTP, ftp, telnet,etc)
Transport
(TCP, UDP, etc)
Network
(IP, etc)
Link
(Device driver)

 

Ports

 

Working with URLs

 

Creating a URL

 

Other URL Constructors

 

MalformedURLException

Each of the four URl constructors will throws a MailformedURLException if there is a null argument or unknown protocol

// Catch and handle this exception by embedding your URL constructor
try
{
	URL myURL = new URL(...)
}
catch
{
	...
	// exception handler code here
	...
}			// We will talk about exception handling in detail later on

 

Parsing a URL

Example:
import java.net.*
import java.io.*

try 
{
	aURL = new URL("http://java.sun.com/");
	System.out.println("protocol = " + aURL.getProtocol());
}
catch (MalformedURLException e)
{
	System.out.println("MalformedURLException:" + e);
}	

 

Reading Directly from a URL

Example:
...
// This part of the java application reads the content from the input stream
// and then echo out the contents to the display
try 
{
	URL myObj = new URL("http://www.openloop.com/");
	BufferedReader dis = new BufferedReader(new InputStreamReader(myObj.openStream()));
	String inputLine;

	while ((inputLine = dis.readLine()) != null)
	{
		System.out.println(inputLine);
	}
	dis.close();
}
catch (MalformedURLException me)
{
	System.out.println("MalformedURLException: " + me);
}
catch (IOException ioe)
{
	System.out.println("IOException: " + ioe);
}

 

Lab

Write a Java application called Week6 that will

  1. Create an URL object with http as protocol and www.yahoo.com as resource name.
  2. Parse the newly created URL object and print out
  3. Then, read directly from the URL object and print out all the contents from the input stream to the display
  4. Run the program by "java Week6 > tempfile", tempfile will hold all the output

Note: Remember to use the try catch block when working with URL and InputStream
Note: Our application *actually* get to the network and download information !!!

Copyright 1996-2001 OpenLoop Computing. All rights reserved.