E N D
DEFINING APPLET • The word applet is meant to suggest a small application. • Applets were intended to be small programs run over the Internet: • However, there are no size constraints on applets. • Applets can be viewed over the Internet, or without any connection to the internet. • An applet is similar to a Swing GUI: • In fact, almost all of the Swing techniques can be used in applets.
An applet class is normally defined as a derived class of the class Japplet. • The class JApplet is in the package javax.swing. • There is also an older class, Applet, which has been superseded by the JApplet class.
An applet class can be designed as a derived class of JApplet in much the same way that regular Swing GUIs are defined as derived classes of Jframe. • However, an applet normally defines no constructors. • The method in it performs the initializations that would be performed in a constructor for a regular Swing GUI • Components can be added to an applet in the same way that a component is added to a JFrame • The method add is used to add components to an applet in the same way that components are added to a JFrame
JApplethas a method named setJMenuBar that behaves the same as the setJMenuBar method of a JFrame • JApplet can also have menu bars added to a JApplet or to a panel that is part of the JApplet using the add method
Inheritance Hierarchy of the Applet Class • Every applet is implemented by creating a subclass of the Applet class.
HOW APPLET DIFFER FROM SWING GUI • Some of the items included in a Swing GUI are not included in an applet • Applets do not contain a main or setVisible method • Applets are displayed automatically by a Web page or an applet viewer • Applets do not have titles • Therefore, they do not use the setTitle method • They are normally embedded in an HTML document, and the HTML document can add any desired title
Applets do not use the setSize method • The HTML document takes care of sizing the applet • Applets do not have a close-window button • Therefore, they do not have a setDefaultCloseOperation method • When the HTML document containing the applet is closed, then the applet is automatically closed
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.
SECURITY RESTRICTION • 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.
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.
CREATING 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 • NOTE: 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).
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.InputStreamobject.
CONNECTING TO 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 . . . }
WRITING TO A URL CONNECTION • 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.
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 • 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
IP ADDRESS ES AND JAVA • Java has a class java.net.InetAddress which abstracts network addresses • Serves three main purposes: • Encapsulates an address • Performs name lookup (converting a host name into an IP address) • Performs reverse lookup (converting the address into a host name)
java.net.InetAddress (1) • Abstraction of a network address • Currently uses IPv4 (a 32 bit address) • Will support other address formats in future • Allows an address to be obtained from a host name and vice versa • Is immutable (is a read-only object) • Create an InetAddress object with the address you need and throw it away when you have finished
java.net.InetAddress (2) • Static construction using a factory method • InetAddressgetByName(String hostName) • hostName can be “host.domain.com.au”, or • hostName can be “130.95.72.134” • InetAddressgetLocalHost() • Some useful methods: • String getHostName() • Gives you the host name (for example “www.sun.com”) • String getHostAddress() • Gives you the address (for example “192.18.97.241”) • InetAddressgetLocalHost() • InetAddress[] getAllByName(String hostName)
java.net.ServerSocket (1) • Listens on well-known port for incoming connections • Creates a dynamically allocated port for each newly established connection • Provides a Socket connected to the new port • Maintains a queue to ensure that prospective clients are not lost
java.net.ServerSocket (2) • Construction: • ServerSocket(int port, int backlog) • Allows up to backlog requests to queue waiting for the server to deal with them • Some useful methods: • Socket accept() • Blocks waiting for a client to attempt to establish a connection • void close() • Called by the server when it is shutting down to ensure that any resources are deallocated • More details in the Javadoc (as always!)
java.net.Socket(1) • Provides access to TCP/IP streams • Bi-directional communication between sender and receiver • Can be used to connect to a remote address and port by using the constructor: • Socket(String remoteHost, int port) • Also used to accept an incoming connection (see ServerSocket)
java.net.Socket (2) • Can obtain access to input and output streams • Input stream allows reception of data from the other party • InputSteamgetInputStream() • Output stream allows dispatch of data to the other party • OutputStreamgetOutputStream()
java.net.DatagramPacket (1) • DatagramPackets normally used as short lived envelopes for datagram messages: • Used to assemble messages before they are dispatched onto the network, • or dismantle messages after they have been received • Has the following attributes: • Destination/source address • Destination/source port number • Data bytes constituting the message • Length of message data bytes
java.net.DatagramPacket (2) • Construction: • DatagramPacket(byte[] data, int length) • Some useful methods: • void setAddress(InetAddressaddr) • InetAddressgetAddress() • void setPort(int port) • intgetPort() • DatagramPackets are not immutable so, in principle you can reuse then, but . . • Experience has shown that they often misbehave when you do -- create a new one, use it once, throw it away!
java.net.DatagramSocket (1) • Used to represent a socket associated with a specific port on the local host • Used to send or receive datagrams • Note: there is no counterpart to java.net.ServerSocket! Just use a DatagramSocket with a agreed port number so others know which address and port to send their datagrams to
java.net.DatagramSocket (2) • Construction: • DatagramSocket(int port) • Uses a specified port (used for receiving datagrams) • DatagramSocket() • Allocate any available port number (for sending) • Some useful methods: • void send(DatagramPacket fullPacket) • Sends the full datagram out onto the network • void receive(DatagramPacket emptyPacket) • Waits until a datagram and fills in emptyPacket with the message • . . . and a few more in the Javadoc
sea.datagram.DatagramSender • This example sends datagrams to a specific host (anywhere on the Internet) • The steps are as follows: • Create a new DatagramPacket • Put some data which constitutes your message in the new DatagramPacket • Set a destination address and port so that the network knows where to deliver the datagram • Create a socket with a dynamically allocated port number (if you are just sending from it) • Send the packet through the socket onto the network
sea.datagram.DatagramSender byte[] data = “This is the message”.getBytes(); DatagramPacket packet = new DatagramPacket(data, data.length); // Create an address InetAddress destAddress = InetAddress.getByName(“fred.domain.com”); packet.setAddress(destAddress); packet.setPort(9876); DatagramSocket socket = new DatagramSocket(); socket.send(packet);
sea.datagram.DatagramReceiver • The steps are the reserve of sending: • Create an empty DatagramPacket (and allocate a buffer for the incoming data) • Create a DatagramSocket on an agreed socket number to provide access to arrivals • Use the socket to receive the datagram (the thread will block until a new datagram arrrives) • Extract the data bytes which make up the message
sea.datagram.DatagramReceiver // Create an empty packet with some buffer space byte[] data = new byte[1500]; DatagramPacket packet = new DatagramPacket(data, data.length); DatagramSocket socket = new DatagramSocket(9876); // This call will block until a datagram arrives socket.receive(packet); // Convert the bytes back into a String and print String message = new String(packet.getData(), 0, packet.getLength()); System.out.println("message is " + message); System.out.println("from " + packet.getAddress());
java.net.MulticastSocket • Subclass of java.net.DatagramSocket • Constructed the same way • Adds some extra methods: • void joinGroup(InetAddress mcastGroup) • Enter the specifies group so that you can send or receive datagrams • void leaveGroup(InetAddress mcastGroup) • Leave a group that you previously joined • void setTimeToLive(int ttl) • Sets how far your datagrams will travel before routers ignore them • int getTimeToLive()
sea.datagram.MulticastSender • Sending similar to the previous example. . • . . .but must register with the multicast group and decide the longevity • The steps involved are: • Create the MulticastSocket. • Join the multicast group(s) (on startup). • Create the DatagramPacket. • Send the packet through the socket. • Leave the multicast group (on exit).
sea.datagram.MulticastSender InetAddress multicastGroup = InetAddress.getByName(multicastGroupAddr); MulticastSocket socket = new MulticastSocket(); socket.joinGroup(multicastGroup); socket.setTimeToLive(5); byte[] data = “This is the message”.getBytes(); DatagramPacket datagram = new DatagramPacket(data, data.length); datagram.setAddress(multicastGroup); datagram.setPort(9876); socket.send(datagram); socket.leaveGroup(multicastGroup);
sea.datagram.MulticastReceiver • The steps are: • Create a multicast socket on an agreed port. • Join the multicast group (on startup). • Create an empty datagram. • Wait for datagram to be delivered on the socket. • Unpack and use the datagram. • Leave the multicast group (on exit).
sea.datagram.MulticastReceiver InetAddress multicastGroup = InetAddress.getByName(multicastGroupAddr); MulticastSocket socket = new MulticastSocket(9876); socket.joinGroup(multicastGroup); byte[] data = new byte[1000]; DatagramPacket packet = new DatagramPacket(data, data.length); socket.receive(packet); String message = new String( packet.getData(), 0, packet.getLength()); socket.leaveGroup(multicastGroup);