Network Programming With Java Hilal Arslan Hale Müge Kıncak.

57
Network Programming With Java Hilal Arslan Hale Müge Kıncak

Transcript of Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Page 1: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Network Programming With Java

Hilal Arslan

Hale Müge Kıncak

Page 2: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

What is Next?

Applets URL Objects Datagram Objects

Page 3: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

What is an Applet

An applet is a program written in the JavaTM programming language that can be included in an HTML page, much in the same way an image is included. When you use a Java technology-enabled browser to view a page that contains an applet, the applet's code is transferred to your system and executed by the browser's Java Virtual Machine (JVM).

Page 4: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Compiling an Applet

C:\>javac Applet1.java

C:\>appletviewer Applet1.html

The Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer. The Applet class provides a standard interface between applets and their environment.

Page 5: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Every applet is implemented by creating a subclass of the Applet class.

Inheritance Hierarchy of the Applet Class

Page 6: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

The Life Cycle of an Applet

Loading The Applet– An instance of the applet's controlling class (an Applet subclass)

is created. – The applet initializes itself.

– The applet starts running

Page 7: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

A Simple Applet

import java.applet.Applet;import java.awt.Graphics;public class Simple extends Applet { StringBuffer buffer; public void init() {

buffer = new StringBuffer(); addItem("initializing... "); } public void start() {

addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) {

//Draw a Rectangle around the applet's display area. g.drawRect(0, 0, size().width - 1, size().height - 1);

//Draw the current string inside the rectangle. g.drawString(buffer.toString(), 5, 15); }

}

Page 8: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Leaving and Returning to the Applet's Page

When the user leaves the page -- for example, to go to another page -- the applet has the option of stopping itself. When the user returns to the page, the applet can start itself again. The same sequence occurs when the user iconifies and then reopens the window that contains the applet. (Other terms used instead of iconify are minaturize, minimize, and close.)

Page 9: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Some browsers let the user reload applets, which consists of unloading the applet and then loading it again. Before an applet is unloaded, it's given the chance to stop itself and then to perform a final cleanup, so that the applet can release any resources it holds

Reloading the Applet

Page 10: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

When the user quits the browser (or whatever application is displaying the applet), the applet has the chance to stop itself and do final cleanup before the browser exits.

Quitting the Browser

Page 11: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

An applet can react to major events in the following ways:

It can initialize itself.

It can start running.

It can stop running.

It can perform a final cleanup, in preparation for being unloaded.

Summary

Page 12: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Methods for Milestones

public class Simple extends Applet { . . . public void init() { . . . } public void start() { . . . } public void stop() { . . . } public void destroy() { . . . } . . .}

Page 13: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Pre-Made UI ComponentsThe AWT supplies the following UI components (the class that implements each component is listed in parentheses):

Buttons (java.awt.Button)

Checkboxes (java.awt.Checkbox)

Single-line text fields (java.awt.TextField)

Larger text display and editing areas (java.awt.TextArea) Methods for Using UI Components in Applets

add

Adds the specified Component.

remove

Removes the specified Component.

setLayout

Sets the layout manager.

Adding UI Components

Page 14: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Security Restrictions

Applets cannot load libraries or define native methods. An applet cannot ordinarily read or write files on the

host that is executing it. An applet cannot make network connections except to

the host that it came from. An applet cannot start any program on the host that is

executing it. An applet cannot read certain system properties. Windows that an applet brings up look different than

windows that an application brings up.

Page 15: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Windows that an applet brings up look different than windows that an application brings up.

Page 16: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Here are some other things that current browers and other applet viewers let applets do:

Applets can usually make network connections to the host they came from.

Applets running within a Web browser can easily cause HTML documents to be displayed.

Applets can invoke public methods of other applets on the same page.

Applets that are loaded from the local file system (from a directory in the user's CLASSPATH) have none of the restrictions that applets loaded over the network do.

Although most applets stop running once you leave their page, they don't have to.

Applet Capabilities

Page 17: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Using the APPLET Tag

Here's the simplest form of the <APPLET> tag:

<APPLET CODE=AppletSubclass.class WIDTH=anInt HEIGHT=anInt>

</APPLET>

When a Java-enabled browser encounters an <APPLET> tag, it reserves a display area of the specified width and height for the applet, loads the bytecodes for the specified Applet subclass, creates an instance of the subclass, and then calls the instance's init and start methods.

Page 18: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Specifying Parameters

Some applets let the user customize the applet's configuration with parameters.

<APPLET CODE="Animator.class" WIDTH=460 HEIGHT=160><PARAM NAME="imageSource" VALUE="images/Beans"><PARAM NAME="backgroundColor" VALUE="0xc0c0c0"><PARAM NAME="endImage" VALUE=10><PARAM NAME="soundSource" VALUE="audio"><PARAM NAME="soundtrack" VALUE="spacemusic.au"><<PARAM NAME="pause" VALUE=200>. . .</APPLET>

Page 19: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

HTML code interpreted only by browsers that don't understand the <APPLET> tag. Alternate HTML code is any text that appears between the <APPLET> and </APPLET> tags, after any <PARAM>

tags. Java-enabled browsers ignore alternate HTML code.

<APPLET CODE="Animator.class" WIDTH=460 HEIGHT=160 ALT="If you could run this applet, you'd see some animation"><PARAM NAME="imageSource" VALUE="images/Beans"><PARAM NAME="backgroundColor" VALUE="0xc0c0c0"><PARAM NAME="endImage" VALUE=10><PARAM NAME="soundSource" VALUE="audio"><PARAM NAME="soundtrack" VALUE="spacemusic.au">Your browser is completely ignoring the &lt;APPLET&gt; tag!</APPLET>

Specifying Alternate HTML Code and

Text

Page 20: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Specifying the Applet Directory

By default, a browser looks for an applet's class and archive files in the same directory as the HTML file that has the <APPLET> tag. Sometimes, however, it's useful to put the applet's files somewhere else. You can use the CODEBASE attribute to tell the browser in which directory the applet's files are located:

<APPLET CODE=Simple.class CODEBASE="example/" WIDTH=500 HEIGHT=20></APPLET>

Page 21: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Finding and Loading Data Files

Applet getCodeBase method:, is a URL that specifies the directory from which the applet's classes were loaded.

Applet getDocumentBase method: specifies the directory of the HTML page that contains the applet.

Unless the <APPLET> tag specifies a code base, both the code base and document base refer to the same directory on the same server.

Image image = getImage(getCodeBase(), "imgDir/a.gif");

Page 22: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

HelloWorld.class c:\deneme HelloWorld.html c:\java

<HTML>

<HEAD>

<TITLE>A Simple Program</TITLE>

</HEAD>

<BODY>

Here is the output of my program:

<APPLET CODE=HelloWorld.class CODEBASE="http://Hilal1/deneme/" WIDTH=150 HEIGHT=25>

</APPLET>

</BODY>

</HTML>

Page 23: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Applets display status lines with the showStatus method. Here's an example of its use:

showStatus("MyApplet: Loading image file " + file);

Have you ever wanted an applet to display formatted HTML text? Here's the easy way to do it:

public void showDocument(java.net.URL url) public void showDocument(java.net.URL url, String targetWindow)

Displaying Short Status Strings and Documents in an Applet

Page 24: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

AppletContext getApplet() method. (by name)

AppletContext getApplets() method

Both methods, if successful, give the caller one or more Applet objects. Once the caller finds an Applet object, the caller can invoke methods on the object.

Sending Messages to Other Applets

Page 25: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

By default, an applet has no name. For an applet to have a name, one must be specified in the HTML code that adds the applet to a page. You can specify an applet's name in two ways:

•By specifying a NAME attribute within the applet's <APPLET> tag. For example:

<APPLET CODEBASE=example/ CODE=Sender.class WIDTH=450 HEIGHT=200 NAME="buddy">. . .</applet>

•By specifying a NAME parameter with a <PARAM> tag. For

example: <APPLET CODEBASE=example/ CODE=Receiver.class WIDTH=450 HEIGHT=35><PARAM NAME="name" value="old pal">. . .</applet>

Finding an Applet by Name: The getApplet Method

Page 26: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Getting SystemProperties

Key Meaning

"java.vendor" Java vendor-specific string

"java.version" Java version number

"os.arch" Operating system architecture

"os.name" Operating system name

"path.separator" Path separator (for example, ":")

To read a system property from within an applet, the applet uses the System class method getProperty. For example:

String newline = System.getProperty("os.name");

Page 27: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

A thread is a single sequential flow of control within a program. However, a thread itself is not a program; it cannot run on its own. Rather, it runs within a program.

Some texts use the name lightweight process instead of thread

Multiple threads in a single program, running at the same time

and performing different tasks.

Threads in Applets

Page 28: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Multiple Threds

Every applet can run in multiple threads.

Many browsers allocate a thread for each applet on a page, using that thread for all calls to the applet's major milestone methods. Some browsers allocate a thread group for each applet, so that it's easy to kill all the threads that belong to a particular applet

Page 29: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Why Would an Applet Need To Create and Use Its Own Threads?

Time Conservation: If an applet performs a time-consuming task, it should create and use its own thread to perform that task.

•Using Threads For Repeatative Tasks

•Using Threads For One Time Initialization

Page 30: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

This page features an example of a server that allows two applets to communicate with each other. The applets don't have to be running on the same page, in the same browser, or on the same computer. As long as the applets originate from the same computer, they can communicate through the server that's running on that originating computer. Here are the source files:

TalkServer.java

TalkClientApplet.java

TalkServerThread.java

www% java TalkServer TalkServer listening on rendezvous port: 36567

Server Application That Executes on the Applet's Host.

Page 31: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Network Programming with Java

1) URL

2)Datagrams

Page 32: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

What Is a URL?

URL(Uniform Resource Locator) is a reference (an address) to a resource on the Internet.

"URL address” ==> an Internet address "URL object” ==> an instance of the URL

class in a program.

Page 33: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Creating a URL

URL gamelan = new URL("http://www.gamelan.com/");

URL(URL baseURL, String relativeURL) URL gamelanGames =

new URL(gamelan, "Gamelan.net.html");

new URL("http", "www.gamelan.com", 80, "pages/Gamelan.network.html");

creates a URL object for the following URL: http://www.gamelan.com:80/pages/Gamelan.network.html

Page 34: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

!

URLs are "write-once" objects. Once

you've created a URL object, you cannot

change any of its attributes (protocol,

host name, filename, or port number).

Page 35: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Parsing a URLimport java.net.*; import java.io.*; public class ParseURL {

public static void main(String[] args) throws Exception {URL aURL = new

URL("http://java.sun.com:80/docs/books/tutorial/intro.html#DOWNLOADING"); System.out.println("protocol = " + aURL.getProtocol());

System.out.println("host = " + aURL.getHost()); System.out.println("filename = " + aURL.getFile()); System.out.println("port = " + aURL.getPort()); System.out.println("ref = " + aURL.getRef());

} }

protocol = http host = java.sun.com filename = /docs/books/tutorial/intro.html port = 80 ref = DOWNLOADING

Page 36: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Reading Directly from a URL

You can call the URL's openStream() method to get a stream from which you can read the contents of the URL.

The openStream() method returns a java.io.InputStream object.

Page 37: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

openStream()import java.net.*; import java.io.*; public class URLReader {

public static void main(String[] args) throws Exception {URL yahoo = new URL("http://www.yahoo.com/"); BufferedReader in = new BufferedReader( new InputStreamReader( yahoo.openStream())); String inputLine; while ((inputLine = in.readLine()) != null)

System.out.println(inputLine); in.close();

} }

The output: either the HTML commands and textual content or the program might hang or you might see an exception stack trace.

Page 38: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Connecting to a URL

URL object's openConnection method is used to connect to a URL.

Connecting to a URL means initializing a communication link between the Java program and the URL over the network.

try { URL yahoo = new URL("http://www.yahoo.com/"); yahoo.openConnection();

} catch (MalformedURLException e) { // new URL() failed . . .

} catch (IOException e) {

// openConnection() failed . . . }

Page 39: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Reading from a URLConnectionimport java.net.*; import java.io.*; public class URLConnectionReader {

public static void main(String[] args) throws Exception { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yc = yahoo.openConnection();

BufferedReader in = new BufferedReader( new

InputStreamReader( yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null)

System.out.println(inputLine); in.close();

} }

The output from this program is identical to the output from the program that opens a stream directly from the URL.

Page 40: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Writing to a URLConnection

Create a URL. Open a connection to the URL. Set output capability on the URLConnection. Get an output stream from the connection. This

output stream is connected to the standard input stream of the cgi-bin script on the server.

Write to the output stream. Close the output stream.

Page 41: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

An example program that runs the backwards script over the network through a URLConnection: import java.io.*;

import java.net.*; public class Reverse {

public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java Reverse string_to_reverse"); System.exit(1); } String stringToReverse = URLEncoder.encode(args[0]); URL url = new URL("http://java.sun.com/cgi-bin/backwards");

URLConnection connection = url.openConnection(); connection.setDoOutput(true);

PrintWriter out = new PrintWriter(connection.getOutputStream()); out.println("string=" + stringToReverse); out.close(); BufferedReader in = new BufferedReader( new InputStreamReader( connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close();

}}

Page 42: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

What Is a Datagram?

A datagram is an independent, self-

contained message sent over the network

whose arrival, arrival time, and content

are not guaranteed.

Page 43: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

URL, SOCKET vs. DATAGRAM

URL or SOCKET Connection-based Reliable Dedicated point-

to-point channel Same order

DATAGRAMS Not connection-based No guarantees about arrival Don’t have a dedicated

point-to-point channel The order is not

guaranteed

Page 44: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

TCP vs. UDP

TCP: a server application

binds a socket to a specific

port number. This has the

effect of registering the

server with the system to

receive all data destined for

that port..

UDP: the datagram packet

contains the port number of

its destination and UDP

routes the packet to the

appropriate application.

Page 45: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

3 important classes

DatagramSocketRepresents a socket for sending and receiving datagram packets.

DatagramPacketRepresents a datagram packet used to implement a connectionless packet delivery service.

MulticastSocketIt is a DatagramSocket, with additional capabilities for joining "groups" of other multicast hosts on the internet. It is useful for sending and receiving IP multicast packets.

Page 46: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Sample Datagram Client and Server The server continuously receives datagram

packets over a datagram socket. Each datagram packet received by the server indicates a client request for a quotation. When the server receives a datagram, it replies by sending a datagram packet that contains a one-line "quote of the moment" back to the client.

Page 47: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

The client application in this example is fairly simple. It sends a single datagram packet to the server indicating that the client would like to receive a quote of the moment. The client then waits for the server to send a datagram packet in response.

Page 48: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Server Application

Two classes implement the server application: QuoteServer

and QuoteServerThread

The QuoteServerimport java.io.*; public class QuoteServer {

public static void main(String[] args) throws IOException { new QuoteServerThread().start();

} }

Page 49: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

QuoteServerThread

import java.io.*;import java.net.*;import java.util.*;public class QuoteServerThread extends Thread { protected DatagramSocket socket = null; protected BufferedReader in = null; protected boolean moreQuotes = true; public QuoteServerThread() throws IOException {

this("QuoteServerThread"); } public QuoteServerThread(String name) throws IOException { super(name); socket = new DatagramSocket(4445); try { in = new BufferedReader(new FileReader("one-liners.txt")); } catch (FileNotFoundException e) { System.err.println("Could not open quote file. Serving time instead."); } }

Page 50: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Run Method public void run() { while (moreQuotes) { try { byte[] buf = new byte[256]; // receive request DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // figure out response String dString = null; if (in == null) dString = new Date().toString(); else dString = getNextQuote(); buf = dString.getBytes();

// send the response to the client at "address" and "port" InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); } catch (IOException e) { e.printStackTrace();

moreQuotes = false; } } socket.close(); }

Page 51: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

GetNextQuote

protected String getNextQuote() { String returnValue = null; try { if ((returnValue = in.readLine()) == null) { in.close();

moreQuotes = false; returnValue = "No more quotes. Goodbye."; } } catch (IOException e) { returnValue = "IOException occurred in server."; } return returnValue; }}

Page 52: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Client Applicationimport java.io.*;import java.net.*;import java.util.*;public class QuoteClient { public static void main(String[] args) throws IOException { if (args.length != 1) { System.out.println("Usage: java QuoteClient "); return; } // get a datagram socket DatagramSocket socket = new DatagramSocket(); // send request byte[] buf = new byte[256]; InetAddress address = InetAddress.getByName(args[0]); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); // get response packet = new DatagramPacket(buf, buf.length); socket.receive(packet);

// display response String received = new String(packet.getData()); System.out.println("Quote of the Moment: " + received); socket.close(); }}

Page 53: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Broadcasting to Multiple Recipients

MulticastSocket is used on the client-side to listen for packets that the server broadcasts to multiple clients.

The QuoteServerimport java.io.*; public class MulticastServer {

public static void main(String[] args) throws IOException { new MulticastServerThread ().start();

} }

Page 54: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

QuoteServerThread

public class MulticastServerThread extends QuoteServerThread { …

}

Run Methodpublic void run() {

while (moreQuotes) { try { byte[] buf new byte[256]; // don't wait for request...just send a quote String dString = null;

if (in == null) dString = new Date().toString();

Page 55: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

else dString = getNextQuote(); buf = dString.getBytes();

InetAddress group = InetAddress.getByName("230.0.0.1"); DatagramPacket packet; packet = new DatagramPacket(buf, buf.length, group, 4446); socket.send(packet); try { sleep((long)Math.random() * FIVE_SECONDS); } catch (InterruptedException e) { } } catch (IOException e) { e.printStackTrace(); moreQuotes = false; }

}socket.close();

}

Page 56: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Client Application

MulticastSocket socket = new MulticastSocket(4446);InetAddress group = InetAddress.getByName("230.0.0.1");socket.joinGroup(group);DatagramPacket packet;for (int i = 0; i < 5; i++) { byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String received = new String(packet.getData()); System.out.println("Quote of the Moment: " + received);}socket.leaveGroup(group);socket.close();

Page 57: Network Programming With Java Hilal Arslan Hale Müge Kıncak.

Thanks!

Any Questions?