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

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 10 Applets.
Advertisements

1 Chapter 9 Network Programming. 2 Overview Java has rich class libraries to support network programming at various levels. There are standard classes.
Client Side Programming Using Java Applet Outcomes: You will be expected to know: – Java Applets and HTML file; –bytecode and platform independent programs;
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
Prepared By E. Musa Alyaman1 URLs, InetAddresses, and URLConnections Chapter 9.
Java Sockets Source:
Applets. The Applet Class public class MyApplet extends java.applet.Applet {... /** The no-arg constructor is called by the browser when the Web page.
Review of Java Applets Vijayan Sugumaran Decision and Information Sciences Oakland University.
1 Java Networking – Part I CS , Spring 2008/9.
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 16 Applets.
1 Java Networking CS , Spring 2008/9. 2 Today’s Menu Networking Basics  TCP, UDP, Ports, DNS, Client-Server Model TCP/IP in Java Sockets URL 
Java Socket Support Presentation by: Lijun Yuan Course Number: cs616.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L24 (Chapter 25) Networking.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 14 Applets, Images,
Projekt współfinansowany przez Unię Europejską w ramach Europejskiego Funduszu Społecznego „Networking”
28-Jun-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
1 Server-Client communication without connection  When the communication consists of sending and/or receiving datagram packets instead of a data stream.
28-Jun-15 Applets. 2 An applet is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 25 Networking.
15-Jul-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L05 (Chapter 16) Applets.
Network Programming in Java David Meredith Aalborg University.
USER DATAGRAM PROTOCOL (UDP) Prof. Crista Lopes. What is UDP ?  an unreliable transport protocol that can be used in the Internet.  an alternative to.
Applets  The Applet Class  The HTML Tag F Passing Parameters to Applets.
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
Building an ftp client and server using sockets we now know enough to build a sophisticated client/server application!  ftp  telnet  smtp  http.
CS 352-Socket Programming & Threads Dept. of Computer Science Rutgers University (Thanks,this slides taken from er06/
Computer Networks  Network - A system of computers interconnected in order to share information.  Data transmission - consists of sending and receiving.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
5 Chapter Five Web Servers. 5 Chapter Objectives Learn about the Microsoft Personal Web Server Software Learn how to improve Web site performance Learn.
JAVA APPLETS By: Ms. Humaira Siddiqui. Java and the Internet Java is considered to be a language well suited to be used in the internet. In contrast with.
Applets Chapter 17.  Java’s big splash onto the scene came in the mid 90’s. The people at Sun Microsystems had managed to work java programs into Web.
Import java.net.*; import java.io.*; public class LowPortScanner { public static void main(String[] args) { String host = "localhost"; if (args.length.
Applets Life Cycle Drawing and Event Handling Methods for UI Components Applet Capabilities Example.
DBI Representation and Management of Data on the Internet.
Chapter 17: Applets, Images, and Sound. Objectives Learn about applets Write an HTML document to host an applet Use the init() method Work with JApplet.
Java Applets. Topics What is an applet? To convert GUI applications to Applets Hello World applet example!! Applets life cycle examples Invoking applets.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Servlet Communication Other Servlets, HTML pages, objects shared among servlets on same server Servlets on another server with HTTP request of the other.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Pravin Yannawar, DOCS, NMU Jalgaon Basic Java : Applets 2 Objectives of This Session Identify the need for Applets Distinguish between Applets and Applications.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
Java applets. Outline What is Java? Java Applications Java Applets Java Applets Securities Summary.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
StreamTokenizer Break up a stream of text into pieces called tokens A token is the smallest unit recognized by a text parsing algorithm (words, symbols,
Chapter 6 Applets and HTML  Overview  HTML tags for Applets  Applet Life Cycle  Applet Class  JAR files.
Chapter 14 Applets and Advanced GUI  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets F.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Networking A network represents interconnection of computers that is capable.
1 Applets. 2 What is an applet? Applet: a Java program that can be inserted into a web page and run by loading that page in a browser brings web pages.
CHAPTER Agenda Applets Servelets Browsers HelloWorld.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
1 Applets Programming. Introduction Java programs are divided into two main categories, applets and applications. An application is an ordinary Java program.
Working with URLs CSIE, National University of Tainan.
Network Programming. These days almost all devices.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 33 Networking.
Socket Programming Ameera Almasoud
Applications Active Web Documents Active Web Documents.
Source: Java Sockets Source:
Block 14 Group Communication (Multicast)
Distributed Computing, M. L. Liu
„Networking”.
Basic Protocols 24-Nov-18.
Java applets 1/3/2019.
Basic Protocols 19-Feb-19.
Exceptions and networking
Presentation transcript:

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

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

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

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.

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

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

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

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

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

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

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

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

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

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.

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

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

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.

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

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

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>

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

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

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

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

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

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

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

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

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

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

Network Programming with Java 1) URL 2)Datagrams

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.

Creating a URL 4 URL gamelan = new URL(" 4 URL(URL baseURL, String relativeURL) URL gamelanGames = new URL(gamelan, "Gamelan.net.html"); 4 new URL("http", " 80, "pages/Gamelan.network.html"); creates a URL object for the following URL:

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

Parsing a URL import java.net.*; import java.io.*; public class ParseURL { public static void main(String[] args) throws Exception { URL aURL = new URL(" 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

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

openStream() import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { URL yahoo = new URL(" 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.

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(" yahoo.openConnection(); } catch (MalformedURLException e) { // new URL() failed... } catch (IOException e) { // openConnection() failed... }

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(" 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.

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.

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

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.

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

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.

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.

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.

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.

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

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

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

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

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

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

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

else dString = getNextQuote(); buf = dString.getBytes(); InetAddress group = InetAddress.getByName(" "); 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(); }

Client Application MulticastSocket socket = new MulticastSocket(4446); InetAddress group = InetAddress.getByName(" "); 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();

Thanks! Any Questions?