14: Applets and the Internet

What We Will Cover


Illuminations

Questions on Sampler Project (5/25/05)?

Questions from last class?

14.1: Applets and the Web

Objectives

At the end of the lesson the student will be able to:

  • Discuss the technologies used on the Web
  • Describe the uses and limitations of applets
  • List the four important applet methods called by the browser

14.1.1: The Internet and the Web

What is the Internet?

  • Internet is a set of networks connected together with routers
  • Networks move data from one computer to another
  • Router are computers that move the data from one network to another

What is the World-Wide Web?

  • The Web is all about delivering hypertext documents over the Internet
  • Hypertext documents are written using Hypertext Markup Language (HTML)
  • Key feature of HTML is the hypertext link
  • Hypertext links connect one document to another

Brief History of the Internet

  • 1969: Internet started by US DOD with 4 computers -- called ARPANET
  • 1983: Internet (1000 computers) split into two parts -- military and University
  • 1987: High-speed backbone added to solve performance issues (10K computers)
  • 1989: World-Wide Web and HTML invented by Tim Berners-Lee at CERN
  • 1992-3: US Government decides to commercialize Internet
  • 1993: first graphical browser invented by Marc Andreessen
    • While a student at the University of Illinois

14.1.2: Web Technology

World-Wide Web Architecture

  • Web has four major components:
    • Web client (e.g. browser): requester of documents and services
    • Web server: provider of services e.g. Web documents
    • Internet: very large network to move the data
    • Files: text, images, sound, video, etc.
  • Browser uses Hypertext Markup Language (HTML) to format a page

Web Browser

  • Web browser is a program that runs on a computer
  • Allows a person to retrieve and display files in various formats
  • For example:
    • Display a text file in HTML format
    • Display picture files that use Graphics Interchange Format (GIF) format
    • Play a sound file in Windows Waveform (WAV) format

HTML

  • HTML files are a mixture of text to display and HTML tags
  • Tags are coded commands that tell the browser how to format the text
  • For example, HTML tags could define text size or color
  • For instance, the following HTML tag changes the text color of red dog
  • <font color="red">red dog</font>
  • HTML tags are shown in bold above
  • Note that tags begin with a less-than sign and end with a greater-than sign

Web Server

  • Web servers are programs that provide web documents
    • Often run on dedicated computers, also known as a web server
  • Web server software runs constantly in the background waiting for requests
  • When a request is received, locates and sends the requested document

Client/server Interaction

  • User enters query (URL) into client (browser)
  • Client connects to server and sends query
  • Server analyzes query, computes results and respond with information
  • Client receives results and displays them to user

14.1.3: Introduction to Applets

Static Documents

  • At first, only static documents were available on the Web
  • Soon became apparent that more technologies were needed
  • Needed to display dynamic content in browsers
    • Graphics
    • Animation
    • Sound

Enter Applets

  • In 1995, Sun Microsystems released Applets
  • Applet: a Java program that runs in a browser
  • People were impressed with applets in Web pages
    • Spinning molecules
    • Sorting demos
  • Both Netscape and Microsoft agreed to support Java applets

Advantages of Applets

  • Applets have several advantages when run in a Web browser
    • Applets work on the client and do not use server resources
    • Applets run in most browsers on most operating systems
    • Can use the full power of the Java programming language
    • Applets are secure, running with tight "sandbox" controls
    • Applets can communicate with the web server

Demonstration Applets

  • Sun has many demonstration applets
  • Can study and mimic source code to learn new features
  • All programmers can learn by reading the source code of existing programs

14.1.4: Applet Deployment Issues

  • When Java 1.0 was released, both IE and Netscape included a JVM
    • Allowed any Web page to run applets
  • Unfortunately, neither browser kept up with newer versions of Java
  • Because of this, while most browsers support Java 1.0, only a few support Java 1.1
    • Thus, most do not support Swing
    • Nor do most of them support recent Java features
  • To allow IE and Netscape to run newer versions of Java, Sun provides a Java Plug-in
  • If the Java Plug-in is installed, the browser can run Swing applets
  • Of course, many Web users have not installed the Java Plug-in
    • People need a strong incentive to bother installing any plug-in
  • Note that the Java Plug-in was automatically installed when you installed Java for this course

Two Solutions

  • One solution is to use Swing applets and install the Java Plug-in
    • On every client machine
  • Another solution is to write applets using the older AWT version of Java

Swing Applets

    Pros

  • Swing applets use Swing components
    • More features
    • Common look and feel
  • Can use all of the latest Java language features
  • Cons

  • Developer must run an HTML Converter program
  • Must install the Java Plug-in on client machines

AWT Applets

    Pros

  • Developer does not need to run an HTML Converter program
  • Do not need to install the Java Plug-in on client machines
  • Cons

  • Cannot use Swing components and event model
  • Must restrict Java features to earliest Java releases (e.g. version 1.0)

Guidelines and Advice

  • Use Swing on Intranets and places where you can be sure the Java Plug-in is installed
  • Use Swing if people have a strong enough interest in your program to install the Java Plug-in
  • Otherwise, use AWT

14.1.5: Applet Security Issues

  • Sun wanted to make sure applets could not damage a client system
  • Built strong security restrictions into applets to limit what they can do

Applet Restrictions

  • Cannot read, write or delete files on the client system
  • Cannot run programs on the client system
  • Can only access a few properties of the client system:
    • Java version
    • Name of operating system
    • Version of operating system
    • Characters used to separate directories, paths and lines
  • Cannot make network connections to servers
    • Other than the one the applet was loaded from

Some Applet Capabilities

  • Display GUI components and graphics
  • Send keystrokes and mouse clicks to the applet's server
  • Make network connections to the applet's server
  • Call public methods of other applets on the same Web page

Bypassing Security

  • Can create signed applets to overcome security restrictions
    • Indicates applet comes from a trusted source
  • User must agree to use a signed applet
  • Further information: Lesson: Quick Tour of Controlling Applets

14.1.6: Applet Construction

Inheritance Chain

  • Following is the inheritance chain for applets
  • Use methods of Component and Container with both types of applets
  • Extend Applet class to create AWT applets
  • Extend JApplet class to create Swing applets
java.awt.Component
  |
  +--java.awt.Container
       |
       +--java.awt.Panel
            |
            +--java.applet.Applet
                 |
                 +--javax.swing.JApplet

Applet Lifecycle Methods

  • Four methods are used to control the execution of an applet
    • All four are methods of the Applet class
  • Browser automatically calls these methods
    • You never need to call them
  • Normally override the init() method in your applet code
  • May also override the other methods

Four Methods of Applet

Method Description
public void init() Called when the browser loads the applet.
public void start() Called after the init method and every time the user moves to the web page with the applet.
public void stop() Called before the destroy method and every time the user leaves the web page with the applet.
public void destroy() Called when the user exits the browser.

14.1.7: Sample Applet

  • You can easily create an applet like the following
  • Code for this applet is:
1
2
3
4
5
6
7
8
import javax.swing.*;

public class HelloApplet extends JApplet {
    public void init() {
        JLabel label = new JLabel("Hello, world!");
        getContentPane().add(label);
    }
}
  • Looking at each piece of code:
  • import javax.swing.*;
    
  • JApplet is part of the Swing class-library
  • Use an import statement to access the library
  • public class HelloApplet extends JApplet {
    
  • Use and override methods defined in JApplet
  • Using inheritance, we can take advantage of the work someone else did
  • public void init() {
    
  • Applets start in an init() method, unlike applications which start in main()
  • By default, init() has an empty body
  • We override (redefine) init() in our HelloApplet class
  • JLabel label = new JLabel("Hello, Applet World!");
    
  • For our simple Applet we only need to display text
  • We use a label class named JLabel for that purpose
  • One of the constructors for JLabel takes our literal string parameter: "Hello, Applet World!"
  • getContentPane().add(label);
    
  • We add our JLabel component to the JApplet container
  • JApplet can now display the text we entered

Exercise 14.1

Take one minute to prepare an answer to the following question:

Use this applet code and for answering the questions that follow:

1
2
3
4
5
6
7
8
import javax.swing.*;

public class HelloApplet extends JApplet {
    public void init() {
        JLabel label = new JLabel("Hello, world!");
        getContentPane().add(label);
    }
}
  1. What type of applet is this: AWT or Swing? How can you tell?
  2. How does the init() method get called?

14.2: Swing Applets

Objectives

At the end of the lesson the student will be able to:

  • Develop and test a Swing applet
  • Code the HTML page for an applet
  • View the applet in a browser and the Applet Viewer

14.2.1: Developing Swing Applets

  • Two ways to develop Swing applets:
    • Develop new applets from scratch
    • Convert existing Swing applications to applets

Developing Swing Applets from Scratch

  1. Write the code and compile the Swing applet
  2. Write the HTML page for the applet
  3. Test the applet with the Applet Viewer
  4. Use the HTML Converter to convert the HTML for the applet
  5. Test the HTML page with a browser

Converting Swing Applications to Applets

  1. Extend the JApplet class rather than the JFrame class
  2. Convert the constructor of the JFrame to the init() method of the applet
  3. Remove any code that:
    • Sets the title, size and position of the frame
    • Exits the frame

For Example

  • To convert the following code to run as an applet:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginPane extends JFrame
        implements ActionListener {

    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

    public static void main(String[] args) {
        new LoginPane();
    }

    public LoginPane() {
        super("Login Pane");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // Set the layout manager
        Container c = getContentPane();
        c.setLayout(new BorderLayout());

        // Create the fields and button
        login = new JTextField(10);
        password = new JPasswordField("asecret");
        loginButton = new JButton("Login");

        // Add components to the container
        c.add(login, BorderLayout.NORTH);
        c.add(password, BorderLayout.CENTER);
        c.add(loginButton, BorderLayout.SOUTH);

        // Add event handlers
        login.addActionListener(this);
        password.addActionListener(this);
        loginButton.addActionListener(this);

        pack();
        setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == login) {
            password.requestFocus();
        } else if ((e.getSource() == password)
                || (e.getSource() == loginButton)) {
            JOptionPane.showMessageDialog(null,
                "Login: " + login.getText()
                + "\nPassword: "
                + new String(password.getPassword()),
                "Login Message",
                JOptionPane.INFORMATION_MESSAGE);
        }
    }
}
  1. Rename LoginPane to LoginApplet
  2. Extend JApplet rather than JFrame
  3. public class LoginApplet extends JApplet
  4. Remove the main() method
  5. Convert the constructor to be the init() method
  6. public void init()
  7. Remove the title set by the call to super()
  8. Remove the setDefaultCloseOperation(EXIT_ON_CLOSE) method call
  9. Remove the pack() and setVisible(true) method calls
  • End result looks like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginApplet extends JApplet
        implements ActionListener {

    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

    public void init() {
        // Set the layout manager
        Container c = getContentPane();
        c.setLayout(new BorderLayout());

        // Create the fields and button
        login = new JTextField(10);
        password = new JPasswordField("asecret");
        loginButton = new JButton("Login");

        // Add components to the container
        c.add(login, BorderLayout.NORTH);
        c.add(password, BorderLayout.CENTER);
        c.add(loginButton, BorderLayout.SOUTH);

        // Add event handlers
        login.addActionListener(this);
        password.addActionListener(this);
        loginButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == login) {
            password.requestFocus();
        } else if ((e.getSource() == password)
                || (e.getSource() == loginButton)) {
            JOptionPane.showMessageDialog(null,
                "Login: " + login.getText()
                + "\nPassword: "
                + new String(password.getPassword()),
                "Login Message",
                JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

Actual Applet

If you cannot see this applet, your browser may not be Java-enabled.

14.2.2: Creating an HTML Page for Applets

About HTML

  • Hypertext Markup Language (HTML) is the language used to create Web pages
  • Web page is just a text file with HTML tags added to it
  • Tags are embedded in the text to control page layout
  • Tags consist of:
    1. "<": opening character of a tag
    2. Command such as html, body or font
    3. ">": closing character of a tag
  • HTML tags are case insensitive: can use either upper or lower case
  • Note that World Wide Web Consortium (W3C) recommends lowercase tags
  • HTML is viewable in all text editors including Notepad
  • Note that most tags come in pairs: opening tag and closing tag
  • Can nest tags, but should close inner tags before closing outer tags

For Example

  • Following is a basic HTML document that includes an applet tag
  • One thing to note is you can view the source HTML of a web page
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
<head>
<title>Login Applet</title>
</head>

<body>
<h1>Login Applet</h1>
<applet code="LoginApplet.class" width=100 height=70>
If you cannot see this applet, your browser may not
be Java-enabled.
</applet>

</body>
</html>

See it

Some HTML Tags

Tag Description
<html></html> Marks the start and end of an HTML page.
<head></head> Marks the start and end of the section of a page that describes the entire document.
<title></title> Defines the title of an HTML page that appears in the title bar of the browser.
<body></body> Marks the start and end of the section that contains text, applets and other information to present.
<h1></h1> Displays the enclosed text as a level-1 (large) header.
<applet></applet> Defines an applet for display in a document. This tag is officially deprecated, but most browsers still support it.
<embed></embed> Defines a plug-in application within the document. Netscape uses this tag to define Swing applets.
<object></object> Defines an object within a document. IE uses this tag to define Swing applets.

Some Attributes of the Applet Tag

Attribute Description
code Specifies the name of the class file to execute.
codebase Specifies the pathname of the applet on the server.
width Specifies the width of the applet in pixels.
height Specifies the height of the applet in pixels.
archive Specifies the archive file (such as a JAR file) that contains class files and other resources.

Further Information

14.2.3: Running the Applet Viewer

  • Applet Viewer is included in the SDK
  • Lets you test an applet before running it in a browser
  • Following is our LoginApplet displayed in the Applet Viewer
  • Note that only the applet is displayed
  • All other text is ignored

Using the Command Prompt

  1. Open a console window or access the command prompt
  2. Change to the directory where the applet class file is located
  3. Type in the command appletviewer followed by the HTML file for the applet
  4. appletviewer LoginApplet.html

14.2.4: Using the Java Plug-in HTML Converter

  • Different browsers run applets using different tags
    • Embed tag for Netscape
    • Object tag for IE
  • Can set up HTML code so that both types of tags are supported
    • Allows applets to run in more browsers
    • Converted page will work for most browsers including Mozilla, Netscape and IE
  • Since coding the HTML is somewhat complex, Sun created a tool
    • Called the Java Plug-in HTML Converter
    • Located in the bin ubdirectory of the Java installation
  • Tool is included with the SDK for this course

For Example

  • For our example, we will convert the LoginApplet.html file shown below
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<html>
<head>
<title>Login Applet</title>
</head>

<body>
<h1>Login Applet</h1>
<applet code="LoginApplet.class" width=100 height=70>
If you cannot see this applet, your browser may not
be Java-enabled.
</applet>

</body>
</html>
  • Locate the HtmlConverter.exe program and start the application
    • Located in the bin ubdirectory of the Java installation
  • Click on the Browse... button to select files
  • Click on the Convert... button to convert a file
  • Note that the Applet Viewer may not display correctly after the conversion

See the converted page and view the source.

More Information

14.2.5: Testing and Debugging a Swing Applet

  • Need to test an applet to see if it works correctly in a browser
  • However, the browser will not show exceptions or System.out.print() statements
  • Sun provides the Java Console to address these issues

Testing a Swing Applet

  • Start your web browser and run the applet
  • If it does not work correctly, start the Java Console
  • You can view any exceptions thrown by the applet in the console window
  • Also you can add System.out.println() statements to the code and view them in the console

Displaying the Java Console

  • How to display the Java Console depends on how you installed it
  • From the Windows task bar, double-click the Java Console icon
  • From IE, select the Tools menu and select Sun Java Console
  • From Netscape, select the Tools menu and of the Communicator menu
  • From Mozilla, select the Tools, Web Development and Java Console

Further Information

14.2.6: Executing as Applets or Applications

  • Previously, we converted applications to applets
  • Also can configure an applet to run as either an applet or application
    • Possible because a JApplet is a Component
    • Thus applets can run in a JFrame
  • Will use the LoginApplet for our example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginApplet extends JApplet
        implements ActionListener {

    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

    public void init() {
        // Set the layout manager
        Container c = getContentPane();
        c.setLayout(new BorderLayout());

        // Create the fields and button
        login = new JTextField(10);
        password = new JPasswordField("asecret");
        loginButton = new JButton("Login");

        // Add components to the container
        c.add(login, BorderLayout.NORTH);
        c.add(password, BorderLayout.CENTER);
        c.add(loginButton, BorderLayout.SOUTH);

        // Add event handlers
        login.addActionListener(this);
        password.addActionListener(this);
        loginButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == login) {
            password.requestFocus();
        } else if ((e.getSource() == password)
                || (e.getSource() == loginButton)) {
            JOptionPane.showMessageDialog(null,
                "Login: " + login.getText()
                + "\nPassword: "
                + new String(password.getPassword()),
                "Login Message",
                JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

For Example

  1. Add a main method to the applet
  2. public static void main(String[] args)
  3. Within main(), Instantiate a JFrame and set the title
  4. JFrame frame = new JFrame("Login Pane");
  5. Set the desired behavior for when the frame closes
  6. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  7. Create an instance of the applet
  8. LoginApp applet = new LoginApp();
  9. Add code to set the size
  10. public static final int WIDTH = 100;
    public static final int HEIGHT = 70;
    ...
    applet.setSize(WIDTH, HEIGHT);
    
  11. Call the init() and start() methods of the applet
  12. applet.init();
    applet.start();
    
  13. Add the applet to the frame
  14. frame.getContentPane().add(applet);
  15. Arrange and display the applet
  16. frame.pack();
    frame.setVisible(true);
    
  • End result looks like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginApp extends JApplet
        implements ActionListener {

    public static final int WIDTH = 100;
    public static final int HEIGHT = 70;
    private JTextField login;
    private JPasswordField password;
    private JButton loginButton;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Login Pane");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        LoginApp applet = new LoginApp();
        applet.setSize(WIDTH, HEIGHT);
        applet.init();
        applet.start();

        frame.getContentPane().add(applet);
        frame.pack();
        frame.setVisible(true);
    }

    public void init() {
        // Set the layout manager
        Container c = getContentPane();
        c.setLayout(new BorderLayout());

        // Create the fields and button
        login = new JTextField(10);
        password = new JPasswordField("asecret");
        loginButton = new JButton("Login");

        // Add components to the container
        c.add(login, BorderLayout.NORTH);
        c.add(password, BorderLayout.CENTER);
        c.add(loginButton, BorderLayout.SOUTH);

        // Add event handlers
        login.addActionListener(this);
        password.addActionListener(this);
        loginButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == login) {
            password.requestFocus();
        } else if ((e.getSource() == password)
                || (e.getSource() == loginButton)) {
            JOptionPane.showMessageDialog(null,
                "Login: " + login.getText()
                + "\nPassword: "
                + new String(password.getPassword()),
                "Login Message",
                JOptionPane.INFORMATION_MESSAGE);
        }
    }
}

Actual Applet

If you cannot see this applet, your browser may not be Java-enabled.

Exercise 14.2

Take one minute to prepare an answer to the following question:

  1. How can the code for a Swing application be converted to a Swing applet?
  2. How is an applet placed in an HTML page?
  3. What is the Applet Viewer?
  4. How can debugging information be displayed when a Swing applet is running?

14.3: Programming for the Internet

Objectives

At the end of the lesson the student will be able to:

  • Discuss how the Internet works
  • Use Java URL objects to locate Internet resources

14.3.1: Packets and the Internet Protocol

  • Networking is about moving data bits from one point to another
  • Internet Protocol (IP) is used to move data in packets
  • Data is bundled into a packet and more bits are added to say where the packet is to go
  • A packet has a limit on its size
  • Applications break up large data and send it in successive packets
  • Every computer connected to the Internet has an address
  • IP uses this address to route packets through the many possible pathways of the Internet

What's My IP Address?

  • Can determine the address of your computer on the Internet
  • On UNIX, run the ifconfig program
  • On Windows, run the ipconfig program
    • From the Start menu, select Run
    • Type in command
    • Type in ipconfig
  • Lists several pieces of information including:
    • Host name
    • IP address

14.3.2: Sending Packets

  • Two common ways to move packets over the Internet are UDP and TCP

UDP

  • Packets can be sent across the Internet using the User Datagram Protocol (UDP)
  • UDP relies on IP for addressing and routing
  • UDP is like mailing packets from the post office
  • IP is what the mail carrier does to route and deliver the packet
  • When we send several packets of postal mail to the same address, we do not know the order in which they arrive
  • It is even possible to lose a packet entirely
  • The same is true for UDP -- packets arrive in any order and can be lost

TCP

  • When we need to guarantee reliable delivery, we can use the Transmission Control Protocol (TCP)
  • TCP uses IP for routing and delivery, just like UDP does
  • However, using TCP is more like making a phone call than sending mail
  • Once a connection is established with TCP, the pathway is held open until all the data is sent
  • The receiving computer verifies receipt by sending messages back to the sender
  • Any lost data is resent until all the packets are received
  • The receiver then puts the packets in the correct order

Tracing Packets

  • Packets are moved over a network by special purpose computers know as routers
  • Every IP packet goes to a nearby router.
  • This router in turn moves the packet to another router closer to the destination
  • This process continues until the packet finally reaches the router serving the destination computer
  • Final router then sends the packet to the destination computer
  • Can examine a packets movement over the Internet
  • On UNIX, run the traceroute program
  • On Windows, run the tracert program
    • From the Start menu, select Run
    • Type in command for Win9X/ME or cmd for WinNT/2000/XP
    • At the command prompt, type tracert and a destination
  • For example:
  • C:\> tracert java.sun.com

    Tracing route to java.sun.com [192.18.97.71]
    over a maximum of 30 hops:

    1 <10 ms 1 ms <10 ms rocky.cabrillo.cc.ca.us [172.16.1.1]
    2 1 ms 1 ms 2 ms seahawk.cabrillo.cc.ca.us [207.62.185.33]
    3 2 ms 2 ms 2 ms 207.62.184.1
    ...
    16 38 ms 38 ms 38 ms java.sun.com [192.18.97.71]

    Trace complete.

  • This shows it took 16 "hops" for packets to travel from my PC to Sun's Java Web site
  • The program sends three test packets to successive routers
  • Measures the time it took for a round trip to each one
  • This listing shows a total travel time of about 38 milliseconds (ms)

14.3.3: Sockets

  • The access device at each end of a phone call is a telephone
  • Similarly, the access object at each end of a TCP/IP session is a socket
  • Java supports both TCP (stream sockets) and UDP (datagram sockets)
  • In addition to the IP Address, sockets also have a port number
  • A port is a software convention the operating system maintains
  • Using a port number allows an incoming request to connect to a specific process
  • Socket connections have both a client end and a server end
  • Servers just listen for a client request on a specific port
  • Clients initiate a connection and then pass a request for information
  • Servers respond to connection requests and return the requested information

14.3.4: Resolving an Address

  • IP Address is like a telephone number
  • Port number is like a telephone extension
  • Together they connect you to a unique destination
  • When a client sends a request, it usually uses a name for the address
  • Domain Name Server (DNS) is used to resolve the name to an IP address
  • Usually one DNS per subnet, campus or company
  • Client application is expected to know the port
  • Common port numbers include the following:
  • Service Port Number
    FTP 20, 21
    Telnet 23
    SMTP (e-mail) 25
    HTTP 80
  • More information on common port numbers available here

The Story of Ping

  • Ping program is used to test whether of not a networked machine is reachable:
  • C:\>ping www.cabrillo.edu
    
    Pinging rocky.cabrillo.edu ...:
    
    Reply from 172.16.1.1: bytes=32 time=1ms TTL=255
    Reply from 172.16.1.1: bytes=32 time<10ms TTL=255
    Reply from 172.16.1.1: bytes=32 time<10ms TTL=255
    Reply from 172.16.1.1: bytes=32 time<10ms TTL=255
    
    Ping statistics for 172.16.1.1:
        Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
    Approximate round trip times in milli-seconds:
        Minimum = 0ms, Maximum =  1ms, Average =  0ms
    
  • There is also an engaging story about ping
  • Scroll down the page and read the Customer Comments on "The Story About Ping"

14.3.5: URLs

Uniform Resource Locator (URL): a standard way of specifying an address on the Internet.

  • URLs consist of two main parts separated by a colon
  • Part before the first colon specifies the access scheme or protocol
  • Part after the colon is interpreted according to the access scheme
  • Usually, two slashes after the colon (//) introduce a hostname
  • Hostnames usually end in a top-level domain name, such as .com
  • Hostnames can be followed by a colon and a port number, for example:
  • http://java.sun.com:80/
    
  • Usually a port number is omitted and the standard port number is used
  • After the hostname comes the pathname
    • Usually related to the pathname of a file on the server

Java URLs

  • Java provide a URL class to represent URLs
  • Easiest way to instantiate a URL is with a String containing the address
  • URL myURL = new URL("http://www.edparrish.com/");
    
  • Once an object exists, one can connect to a site using the method openStream()
  • try {
        URL java = new URL("http://www.edparrish.com/");
        BufferedReader in = new BufferedReader(
            new InputStreamReader(
            myURL.openStream()));
    } catch (MalformedURLException e) { // URL() failed
        . . .
    } catch (IOException e) { // openConnection() failed
        . . .
    }
    
  • Will look at an application of URL in the following section

For Example

  • Following program reads a page from a URL
  • Output looks like the view source from a browser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.net.*;
import java.io.*;

public class URLReader {
    public static void main(String[] args)
            throws Exception {
        URL myURL = new URL("http://www.edparrish.com/");
        BufferedReader in = new BufferedReader(
              new InputStreamReader(
              myURL.openStream()));

        String inputLine;

        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);

        in.close();
    }
}

Further Information

14.3.6: A Simple Web Browser

  • Now that we can read data over the Internet, let's make a Web browser
  • Basic user interface for a Web browser has two components:
    • Text field to get a URL from the user
    • Display area to show the contents of the resource
  • JEditorPane is a Swing component to display or edit various types of content
    • Understands how to display HTML 3.2, among other content types
  • Can load a JEditorPane with content from a URL using method setPage()
    • Method setPage() accepts URLs in either URL or String format
  • JEditorPane will generate a HyperlinkEvent when a hyperlink is clicked
  • Thus, can construct a simple Web browser using:
    • JTextField for the address bar
    • JEditorPane for displaying a Web page
  • Following is adapted from the textbook
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;

public class SimpleBrowser extends JFrame {
    final String home = "http://edparrish.com";
    private JTextField addressField;
    private JEditorPane contentsPane;

    public SimpleBrowser() {
        super("Simple Web Browser");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container c = getContentPane();

        // create the address bar
        addressField = new JTextField(home);
        addressField.addActionListener(
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    loadPage(e.getActionCommand());
                }
            }
        );
        c.add(addressField, BorderLayout.NORTH);

        // create viewing area
        contentsPane = new JEditorPane();
        contentsPane.setEditable(false);
        contentsPane.addHyperlinkListener(
            new HyperlinkListener() {
                // if user clicked hyperlink, go to the page
                public void hyperlinkUpdate(HyperlinkEvent e) {
                    if (e.getEventType() ==
                            HyperlinkEvent.EventType.ACTIVATED)
                        loadPage(e.getURL().toString());
                }
            }
        );
        JScrollPane sp = new JScrollPane(contentsPane);
        c.add(sp, BorderLayout.CENTER);
        loadPage(home);

        setSize(400, 300);
        setVisible(true);
    }

    private void loadPage(String location) {
        // load document into contentsPane and display
        // location in addressField
        try {
            contentsPane.setPage(location);
            addressField.setText(location);
        } catch (IOException ioe) {
            JOptionPane.showMessageDialog(this,
                "Error retrieving specified URL",
                "Bad URL", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String args[]) {
        new SimpleBrowser();
    }
}

Exercise 14.3

Take one minute to prepare an answer to the following question:

  1. The following is a stanza from the document, "What if Dr. Seuss wrote technical manuals?" From a socket standpoint, what is wrong with the verse?

If a packet hits a pocket on a socket on a port,
And the bus is interrupted as a very last resort,
And the address of the memory makes your floppy disk abort,
Then the socket packet pocket has an error to report!

14.4: Using Sockets

Objectives

At the end of the lesson the student will be able to:

  • Create client sockets
  • Create server sockets
  • Communicate between clients and servers

14.4.1: More About Sockets

  • When writing client-server applications, you usually work with sockets
  • In client-server applications, the server provides some service such as:
    • Provide current stock prices
    • Query databases
    • Sending time of day
  • Client uses the service provided by the server
    • Makes the initial request to the server
    • Displays the results of the request

  • Communication between a client and server is done over TCP
  • Both the client and the server must bind a socket to its end of the connection
  • To communicate, the client and server each reads from and writes to its socket

14.4.2: Creating a Client Socket

    Four steps to create a simple client in Java

  1. Create a Socket object for the client
  2. String hostName = "localhost";
    int port = 80;
    Socket sock = new Socket(hostName, port);
    
  3. Obtain socket’s InputStream and OutputStream
  4. InputStreamReader isr =
        new InputStreamReader(sock.getInputStream());
    PrintWriter pw =
        new PrintWriter(sock.getOutputStream());
    

    Should also buffer the streams.

  5. Communicate
  6. in.readLine();
  7. Close streams and Socket
  8. out.close();
    in.close();
    sock.close();
    

For Example

  • Following is an example of a client in Java
  • Connects to a time server and requests the time
  • Displays the time it received
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.io.*;
import java.net.*;

class TimeClient {
    public static void main(String[] args)
            throws Exception {
        String hostName = "sundial.columbia.edu";
        int port = 13;
        Socket sock = new Socket(hostName, port); //1
        BufferedReader in =                //2
            new BufferedReader(
                new InputStreamReader(
                    sock.getInputStream()));

        String timestamp = in.readLine();  //3
        System.out.println(hostName + " say it is "
            + timestamp);

        in.close();                        //4
        sock.close();
    }
}
  • Another time server is: timex.cs.columbia.edu
  • Time servers change often, so search on "Public NTP servers" for a current list

14.4.3: Creating a Server Socket

    Five steps to create a simple server in Java:

  1. Create a ServerSocket object
  2. int portnum = 80;
    ServerSocket server =
        new ServerSocket(portnum);
    
    • Registers an available port
  3. Wait for a connection
  4. Socket conn = server.accept();
    
    • Server blocks until client connects
  5. Get an OutputStream to send and InputStream to receive data
  6. InputStreamReader isr =
        new InputStreamReader(conn.getInputStream());
    PrintWriter pw =
        new PrintWriter(conn.getOutputStream());
    
    • Should buffer the streams
  7. Process request
    • Server and Client communicate via streams
  8. Close streams and connections
  9. out.close();
    in.close();
    conn.close();
    

For Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.io.*;
import java.net.*;
import java.sql.Timestamp;
import java.util.Date;

class TimeServer {
    ServerSocket server;

    public static void main(String[] args) {
        TimeServer ss = new TimeServer(6000);
        ss.runServer();
    }

    TimeServer(int portnum) {
        try {
            server = new ServerSocket(portnum);
        } catch (IOException e) {
            System.out.println(
                "Could not listen on port: "
                + portnum + ", " + e);
            System.exit(1);
        }
        System.out.println("Listening on port "
            + portnum);
    }

    public void runServer() {
        Socket sock = null;
        try {
            sock = server.accept();
            processConnection(sock);
        } catch (IOException e) {
            System.out.println("Server failed: "
                + server.getLocalPort() + ", " + e);
            System.exit(1);
        }
    }

    public void processConnection(Socket sock)
            throws IOException {
        BufferedReader in = new BufferedReader(
            new InputStreamReader(
                sock.getInputStream()));

        PrintWriter out =
            new PrintWriter(sock.getOutputStream());
        System.out.println("Connection extablished");

        Timestamp ts =
            new Timestamp(new Date().getTime());
        out.println(ts);
        System.out.println("Sent to client: " + ts);

        out.close();
        in.close();
        sock.close();
        System.out.println("Finished processing");
    }

}
  • Can adapt our previous client to use our new server
  • String hostName = "localhost"; //1
    int port = 6000;
    

    14.4.4: Client/Server Chat Application

    • Textbook has example client/server chat application
    • Uses stream sockets as described in last two sections
    • Server available here
    • Client available here

    Exercise 14.4

    Take one minute to prepare an answer to the following question:

    How could we provide a server to handle multiple connections?

    14.5: Server-Side Java

    Objectives

    At the end of the lesson the student will be able to:

    • Discuss common uses for Java on the Server
    • Run Java servlets

    14.5.1: About Server-Side Java

    • Server-side Java is one of the most active Java development areas
    • Makes use of networking capabilities with new applications
    • Servlets run as part of an HTTP server and respond to client requests
      • Makes it easy to process client requests using Java programs
    • An extension to Java Servlets is Java Server Pages (JSP)
      • Can combine fixed HTML content with dynamic Java code
      • Simpler to use than pure servlets
    • Several Java servers available that support servlets and JSP
    • Following link has several such servers:
      A Comparison of Java Application Servers
    • Many of these products are open source or free

    14.5.2: Installing a Java Server

    • Server for demonstration is named Tomcat
    • Tomcat is used in the official Reference Implementation for Java Servlet and JavaServer Pages
    • Do not need to configure and run a separate web server
    • Released under an Open Source License, so it is free for commercial use and distribution

    Download the Server

    Start the Server

    • Installation process should start Tomcat for us
    • If not, we start it from the Taskbar
    • Can now access our Java server with a browser at http://localhost:8080/

    14.5.3: Servlets

    • Once the server is running, we can access the Servlet Examples with Code
    • Servlets allow Java classes to take control of an HTTP request
    • Must import Java I/O and Servlet libraries
    • import java.io.*;
      import javax.servlet.*;
      import javax.servlet.http.*;
      
    • Create a servlet by extending HttpServlet class
    • public class HelloWorld extends HttpServlet {
      
    • Then must override the doGet() method
    • public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
          throws IOException, ServletException
      
    • Client request information contained in the HttpServletRequest object
    • Use HttpServletResponse object to return results to the client

    Further Information

    14.5.4: Java Server Pages

    Wrap Up

    Home | WebCT | Announcements | Schedule | Room Policies | Course Info
    Help | FAQ's | HowTo's | Links

    Last Updated: May 18 2005 @19:06:05