Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Network Programming With Java Hilal Arslan Hale Müge Kıncak."— Presentation transcript:

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

2 What is Next? 4 Applets 4 URL Objects 4 Datagram Objects

3 What is an Applet An applet is a program written in the Java TM 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).

4 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.

5 Every applet is implemented by creating a subclass of the Applet class. Inheritance Hierarchy of the Applet Class

6 The Life Cycle of an Applet 4 Loading The Applet –An instance of the applet's controlling class (an Applet subclass ) is created. –The applet initializes itself. –The applet starts running

7 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); }

8 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.)

9 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

10 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

11 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

12 Methods for Milestones public class Simple extends Applet {... public void init() {... } public void start() {... } public void stop() {... } public void destroy() {... }... }

13 Pre-Made UI Components The 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

14 Security Restrictions 4 Applets cannot load libraries or define native methods. 4 An applet cannot ordinarily read or write files on the host that is executing it. 4 An applet cannot make network connections except to the host that it came from. 4 An applet cannot start any program on the host that is executing it. 4 An applet cannot read certain system properties. 4 Windows that an applet brings up look different than windows that an application brings up.

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

16 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

17 Using the APPLET Tag Here's the simplest form of the tag: When a Java-enabled browser encounters an 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.

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

19 HTML code interpreted only by browsers that don't understand the tag. Alternate HTML code is any text that appears between the and tags, after any 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"> Your browser is completely ignoring the <APPLET> tag! Specifying Alternate HTML Code and Text

20 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 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>

21 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 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");

22 HelloWorld.class c:\deneme HelloWorld.html c:\java A Simple Program Here is the output of my program:

23 Applets display status lines with the showStatus method. Here's an example of its use: showStatus 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

24 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

25 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 tag. For example:... By specifying a NAME parameter with a tag. For example: < APPLET CODEBASE=example/ CODE=Receiver.class WIDTH=450 HEIGHT=35>... Finding an Applet by Name: The getApplet Method

26 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 ");

27 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

28 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

29 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

30 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.

31 Network Programming with Java 1) URL 2)Datagrams

32 What Is a URL? URL(Uniform Resource Locator) is a reference (an address) to a resource on the Internet. 4 "URL address” ==> an Internet address 4 "URL object” ==> an instance of the URL class in a program.

33 Creating a URL 4 URL gamelan = new URL("http://www.gamelan.com/"); 4 URL(URL baseURL, String relativeURL) URL gamelanGames = new URL(gamelan, "Gamelan.net.html"); 4 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

34 ! 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).

35 Parsing a URL import 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

36 Reading Directly from a URL 4 You can call the URL's openStream() method to get a stream from which you can read the contents of the URL. 4 The openStream() method returns a java.io.InputStream object. java.io.InputStream

37 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.

38 Connecting to a URL 4 URL object's openConnection method is used to connect to a URL. 4 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... }

39 Reading from a URLConnection import 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.

40 Writing to a URLConnection 4 Create a URL. 4 Open a connection to the URL. 4 Set output capability on the URLConnection. 4 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. 4 Write to the output stream. 4 Close the output stream.

41 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(); }

42 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.

43 URL, SOCKET vs. DATAGRAM URL or SOCKET 4 Connection-based 4 Reliable 4 Dedicated point- to-point channel 4 Same order DATAGRAMS 4 Not connection-based 4 No guarantees about arrival 4 Don’t have a dedicated point-to-point channel 4 The order is not guaranteed

44 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.

45 3 important classes 4 DatagramSocket Represents a socket for sending and receiving datagram packets. 4 DatagramPacket Represents a datagram packet used to implement a connectionless packet delivery service. 4 MulticastSocket It 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.

46 Sample Datagram Client and Server 4 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.

47 4 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.

48 Server Application Two classes implement the server application: QuoteServer and QuoteServerThread 4 The QuoteServer import java.io.*; public class QuoteServer { public static void main(String[] args) throws IOException { new QuoteServerThread().start(); }

49 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."); }

50 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(); }

51 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; }

52 Client Application import 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(); }

53 Broadcasting to Multiple Recipients 4 MulticastSocket is used on the client-side to listen for packets that the server broadcasts to multiple clients. 4 The QuoteServer import java.io.*; public class MulticastServer { public static void main(String[] args) throws IOException { new MulticastServerThread ().start(); }

54 QuoteServerThread public class MulticastServerThread extends QuoteServerThread { … } 4 Run Method public 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();

55 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(); }

56 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();

57 Thanks! Any Questions?


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

Similar presentations


Ads by Google