1 / 57

Network Programming With Java

Network Programming With Java. Hilal Arslan Hale Müge Kıncak. What is Next?. Applets URL Objects Datagram Objects. What is an Applet.

gita
Download Presentation

Network Programming With Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. What is Next? • Applets • URL Objects • Datagram Objects

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

  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. Inheritance Hierarchy of the Applet Class Every applet is implemented by creating a subclass of the Applet class.

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

  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. Reloading the Applet 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

  10. Quitting the Browser • 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.

  11. Summary • 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.

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

  13. Adding UI Components • 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.

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

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

  16. Applet Capabilities • 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.

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

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

  19. Specifying Alternate HTML Code and Text 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>

  20. Specifying the Applet Directory <APPLET CODE=Simple.class CODEBASE="example/" WIDTH=500 HEIGHT=20> </APPLET> 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:

  21. Finding and Loading Data Files • AppletgetCodeBase 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. Image image = getImage(getCodeBase(), "imgDir/a.gif"); Unless the <APPLET> tag specifies a code base, both the code base and document base refer to the same directory on the same server.

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

  23. Displaying Short Status Strings and Documents in an Applet 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 voidshowDocument(java.net.URL url, String targetWindow)

  24. Sending Messages to Other Applets 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.

  25. Finding an Applet by Name: The getApplet Method • 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>

  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. Threads in Applets 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.

  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. Server Application That Executes on the Applet's Host. 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

  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. • "URL address” ==> an Internet address • "URL object” ==> an instance of the URL class in a program.

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

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

  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 • 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 . . . }

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

  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 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 URL, SOCKET vs. DATAGRAM

  44. 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. TCP vs. UDP

  45. 3 important classes • DatagramSocket Represents a socket for sending and receiving datagram packets. • DatagramPacket Represents a datagram packet used to implement a connectionless packet delivery service. • 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 • 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. 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 • 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(); }

More Related