networking applet

18

Click here to load reader

Upload: anonymous-8fcylm

Post on 02-Jun-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 1/18

NETWORK PROGRAMMING

The term network programming refers to writing programs that execute across multiple devices (computers), in whthe devices are all connected to each other using a network.

The java.net package of the J2S !"#s contains a collection of classes and interfaces that provide the low$levelcommunication details, allowing %ou to write programs that focus on solving the pro&lem at hand.

The java.net package provides support for the two common network protocols'

T"' T" stands for Transmission ontrol "rotocol, which allows for relia&le communication &etween twoapplications. T" is t%picall% used over the #nternet "rotocol, which is referred to as T"#".

*+"' *+" stands for *ser +atagram "rotocol, a connection$less protocol that allows for packets of data to &etransmitted &etween applications.

This tutorial gives good understanding on the following two su&jects'

Socket "rogramming' This is most widel% used concept in etworking and it has &een explained in ver% detail.

*- "rocessing' This would &e covered separatel%. lick here to learn a&out *- "rocessing in Java language.

Socket "rogramming'

Sockets provide the communication mechanism &etween two computers using T". ! client program creates a sockon its end of the communication and attempts to connect that socket to a server.

/hen the connection is made, the server creates a socket o&ject on its end of the communication. The client andserver can now communicate &% writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the servprogram to listen for clients and esta&lish connections with them.

The following steps occur when esta&lishing a T" connection &etween two computers using sockets'

The server instantiates a ServerSocket o&ject, denoting which port num&er communication is to occur on.

The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to thserver on the given port.

!fter the server is waiting, a client instantiates a Socket o&ject, specif%ing the server name and port num&er toconnect to.

The constructor of the Socket class attempts to connect the client to the specified server and port num&er. #fcommunication is esta&lished, the client now has a Socket o&ject capa&le of communicating with the server.

0n the server side, the accept() method returns a reference to a new socket on the server that is connected to theclient1s socket.

!fter the connections are esta&lished, communication can occur using #0 streams. ach socket has &oth an0utputStream and an #nputStream. The client1s 0utputStream is connected to the server1s #nputStream, and the clien#nputStream is connected to the server1s 0utputStream.

T" is a twowa% communication protocol, so data can &e sent across &oth streams at the same time. There arefollowing usefull classes providing complete set of methods to implement sockets.

Page 2: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 2/18

ServerSocket lass ethods'

The java.net.ServerSocket class is used &% server applications to o&tain a port and listen for client re3uests

The ServerSocket class has four constructors'S ethods with +escription4 pu&lic ServerSocket(int port) throws #0xception!ttempts to create a server socket &ound to the specified port. !n exception occurs if the port is alread% &ound &%another application.2 pu&lic ServerSocket(int port, int &acklog) throws #0xception

Similar to the previous constructor, the &acklog parameter specifies how man% incoming clients to store in a wait3ueue.5 pu&lic ServerSocket(int port, int &acklog, #net!ddress address) throws #0xceptionSimilar to the previous constructor, the #net!ddress parameter specifies the local #" address to &ind to. The#net!ddress is used for servers that ma% have multiple #" addresses, allowing the server to specif% which of its #"addresses to accept client re3uests on6 pu&lic ServerSocket() throws #0xceptionreates an un&ound server socket. /hen using this constructor, use the &ind() method when %ou are read% to &ind tserver socket

#f the ServerSocket constructor does not throw an exception, it means that %our application has successfull% &ound

the specified port and is read% for client re3uests.

7ere are some of the common methods of the ServerSocket class'S ethods with +escription4 pu&lic int getocal"ort()-eturns the port that the server socket is listening on. This method is useful if %ou passed in 8 as the port num&er inconstructor and let the server find a port for %ou.2 pu&lic Socket accept() throws #0xception/aits for an incoming client. This method &locks until either a client connects to the server on the specified port orthe socket times out, assuming that the time$out value has &een set using the setSoTimeout() method. 0therwise, thmethod &locks indefinitel%

5 pu&lic void setSoTimeout(int timeout)Sets the time$out value for how long the server socket waits for a client during the accept().6 pu&lic void &ind(Socket!ddress host, int &acklog)9inds the socket to the specified server and port in the Socket!ddress o&ject. *se this method if %ou instantiated thServerSocket using the no$argument constructor.

/hen the ServerSocket invokes accept(), the method does not return until a client connects. !fter a client doesconnect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to this new Socket. !T" connection now exists &etween the client and server, and communication can &egin.Socket lass ethods'

The java.net.Socket class represents the socket that &oth the client and server use to communicate with each other.The client o&tains a Socket o&ject &% instantiating one, whereas the server o&tains a Socket o&ject from the returnvalue of the accept() method.

The Socket class has five constructors that a client uses to connect to a server'S ethods with +escription4 pu&lic Socket(String host, int port) throws *nknown7ostxception, #0xception.This method attempts to connect to the specified server at the specified port. #f this constructor does not throw anexception, the connection is successful and the client is connected to the server.2 pu&lic Socket(#net!ddress host, int port) throws #0xceptionThis method is identical to the previous constructor, except that the host is denoted &% an #net!ddress o&ject.

5 pu&lic Socket(String host, int port, #net!ddress local!ddress, int local"ort) throws #0xception.onnects to the specified host and port, creating a socket on the local host at the specified address and port.

Page 3: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 3/18

6 pu&lic Socket(#net!ddress host, int port, #net!ddress local!ddress, int local"ort) throws #0xception.This method is identical to the previous constructor, except that the host is denoted &% an #net!ddress o&ject insteaof a String: pu&lic Socket()reates an unconnected socket. *se the connect() method to connect this socket to a server.

/hen the Socket constructor returns, it does not simpl% instantiate a Socket o&ject &ut it actuall% attempts to conneto the specified server and port.

Some methods of interest in the Socket class are listed here. otice that &oth the client and server have a Socket

o&ject, so these methods can &e invoked &% &oth the client and server.S ethods with +escription4 pu&lic void connect(Socket!ddress host, int timeout) throws #0xceptionThis method connects the socket to the specified host. This method is needed onl% when %ou instantiated the Sockeusing the no$argument constructor.2 pu&lic #net!ddress get#net!ddress()This method returns the address of the other computer that this socket is connected to.5 pu&lic int get"ort()-eturns the port the socket is &ound to on the remote machine.6 pu&lic int getocal"ort()-eturns the port the socket is &ound to on the local machine.

: pu&lic Socket!ddress get-emoteSocket!ddress()-eturns the address of the remote socket.; pu&lic #nputStream get#nputStream() throws #0xception-eturns the input stream of the socket. The input stream is connected to the output stream of the remote socket.< pu&lic 0utputStream get0utputStream() throws #0xception-eturns the output stream of the socket. The output stream is connected to the input stream of the remote socket= pu&lic void close() throws #0xceptionloses the socket, which makes this Socket o&ject no longer capa&le of connecting again to an% server #net!ddress lass ethods'

This class represents an #nternet "rotocol (#") address. 7ere are following usefull methods which %ou would need

while doing socket programming'S ethods with +escription4 static #net!ddress get9%!ddress(&%te>? addr)-eturns an #net!ddress o&ject given the raw #" address .2 static #net!ddress get9%!ddress(String host, &%te>? addr)reate an #net!ddress &ased on the provided host name and #" address.5 static #net!ddress get9%ame(String host)+etermines the #" address of a host, given the host1s name.6 String get7ost!ddress()-eturns the #" address string in textual presentation.: String get7ostame()

@ets the host name for this #" address.; static #net!ddress #net!ddress getocal7ost()-eturns the local host.< String toString()onverts this #" address to a String.Socket lient xample'

The following @reetinglient is a client program that connects to a server &% using a socket and sends a greeting, athen waits for a response.

Aile ame @reetinglient.java

import java.net.BC

Page 4: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 4/18

import java.io.BC

pu&lic class @reetinglientD

pu&lic static void main(String >? args)D

String serverame E args>8?Cint port E #nteger.parse#nt(args>4?)Ctr%D

S%stem.out.println(Fonnecting to F G serverameG F on port F G port)C

Socket client E new Socket(serverame, port)CS%stem.out.println(FJust connected to F

G client.get-emoteSocket!ddress())C0utputStream outToServer E client.get0utputStream()C+ata0utputStream out E

new +ata0utputStream(outToServer)C

out.write*TA(F7ello from FG client.getocalSocket!ddress())C

#nputStream inAromServer E client.get#nputStream()C+ata#nputStream in E

new +ata#nputStream(inAromServer)CS%stem.out.println(FServer sa%s F G in.read*TA())Cclient.close()C

Hcatch(#0xception e)D

e.printStackTrace()CH

HH

Socket Server xample'

The following @reetingServer program is an example of a server application that uses the Socket class to listen forclients on a port num&er specified &% a command$line argument'

Aile ame @reetingServer.java

import java.net.BCimport java.io.BC

pu&lic class @reetingServer extends ThreadD

private ServerSocket serverSocketC

 pu&lic @reetingServer(int port) throws #0xceptionD

serverSocket E new ServerSocket(port)CserverSocket.setSoTimeout(48888)C

H

pu&lic void run()

Dwhile(true)

Page 5: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 5/18

Dtr%D

S%stem.out.println(F/aiting for client on port F GserverSocket.getocal"ort() G F...F)CSocket server E serverSocket.accept()CS%stem.out.println(FJust connected to F

G server.get-emoteSocket!ddress())C+ata#nputStream in E

new +ata#nputStream(server.get#nputStream())C

S%stem.out.println(in.read*TA())C+ata0utputStream out E

new +ata0utputStream(server.get0utputStream())Cout.write*TA(FThank %ou for connecting to FG server.getocalSocket!ddress() G FIn@ood&%eF)C

server.close()CHcatch(SocketTimeoutxception s)D

S%stem.out.println(FSocket timed outF)C&reakC

Hcatch(#0xception e)

De.printStackTrace()C&reakC

HH

Hpu&lic static void main(String >? args)D

int port E #nteger.parse#nt(args>8?)Ctr%D

Thread t E new @reetingServer(port)Ct.start()C

Hcatch(#0xception e)D

e.printStackTrace()CH

HH

ompile client and server and then start server as follows'

K java @reetingServer ;8;;/aiting for client on port ;8;;...

heck client program as follows'

K java @reetinglient localhost ;8;;onnecting to localhost on port ;8;;Just connected to localhost42<.8.8.4';8;;Server sa%s Thank %ou for connecting to 42<.8.8.4';8;;@ood&%e

To send an e$mail using %our Java !pplication is simple enough &ut to start with %ou should have Javaail !"# anJava !ctivation Aramework (J!A) installed on %our machine.

Page 6: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 6/18

Lou can download latest version of Javaail (Mersion 4.2) from Java1s standard we&site.

Lou can download latest version of J!A (Mersion 4.4.4) from Java1s standard we&site.

+ownload and unNip these files, in the newl% created top level directories %ou will find a num&er of jar files for &otthe applications. Lou need to add mail.jar and activation.jar files in %our !SS"!T7.

Send a Simple $mail'

7ere is an example to send a simple e$mail from %our machine. 7ere it is assumed that %our localhost is connectedthe internet and capa&le enough to send an email.

Aile ame Sendmail.java

import java.util.BCimport javax.mail.BCimport javax.mail.internet.BCimport javax.activation.BC

pu&lic class SendmailD

pu&lic static void main(String >? args)D

-ecipient1s email #+ needs to &e mentioned.String to E Fa&cdOgmail.comFC

Sender1s email #+ needs to &e mentionedString from E Fwe&Ogmail.comFC

!ssuming %ou are sending email from localhostString host E FlocalhostFC

@et s%stem properties"roperties properties E S%stem.get"roperties()C

Setup mail server properties.set"ropert%(Fmail.smtp.hostF, host)C

@et the default Session o&ject.Session session E Session.get+efault#nstance(properties)C

tr%D reate a default imeessage o&ject.imeessage message E new imeessage(session)C

Set Arom' header field of the header.message.setArom(new #nternet!ddress(from))C

Set To' header field of the header.message.add-ecipient(essage.-ecipientT%pe.T0,

new #nternet!ddress(to))C

Set Su&ject' header field

Page 7: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 7/18

message.setSu&ject(FThis is the Su&ject ineF)C

ow set the actual messagemessage.setText(FThis is actual messageF)C

Send messageTransport.send(message)CS%stem.out.println(FSent message successfull%....F)C

Hcatch (essagingxception mex) Dmex.printStackTrace()C

HH

H

ompile and run this program to send a simple e$mail'

K java SendmailSent message successfull%....

#f %ou want to send an e$mail to multiple recipients then following methods would &e used to specif% multiple e$ma#+s'

void add-ecipients(essage.-ecipientT%pe t%pe,!ddress>? addresses)

throws essagingxception

7ere is the description of the parameters'

t%pe' This would &e set to T0, or 9. 7ere represents ar&on op% and 9 represents 9lack ar&onop%. xample essage.-ecipientT%pe.T0

addresses' This is the arra% of email #+. Lou would need to use #nternet!ddress() method while specif%ing emai

#+s

Send an 7T $mail'

7ere is an example to send an 7T email from %our machine. 7ere it is assumed that %our localhost is connectedthe internet and capa&le enough to send an email.

This example is ver% similar to previous one, except here we are using setontent() method to set content whosesecond argument is FtexthtmlF to specif% that the 7T content is included in the message.

*sing this example, %ou can send as &ig as 7T content %ou like.

Aile ame Send7Tmail.java

import java.util.BCimport javax.mail.BCimport javax.mail.internet.BCimport javax.activation.BC

pu&lic class Send7TmailD

pu&lic static void main(String >? args)

D

Page 8: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 8/18

-ecipient1s email #+ needs to &e mentioned.String to E Fa&cdOgmail.comFC

Sender1s email #+ needs to &e mentionedString from E Fwe&Ogmail.comFC

!ssuming %ou are sending email from localhostString host E FlocalhostFC

@et s%stem properties

"roperties properties E S%stem.get"roperties()C

Setup mail server properties.set"ropert%(Fmail.smtp.hostF, host)C

@et the default Session o&ject.Session session E Session.get+efault#nstance(properties)C

tr%D reate a default imeessage o&ject.imeessage message E new imeessage(session)C

Set Arom' header field of the header.message.setArom(new #nternet!ddress(from))C

Set To' header field of the header.message.add-ecipient(essage.-ecipientT%pe.T0,

new #nternet!ddress(to))C

Set Su&ject' header fieldmessage.setSu&ject(FThis is the Su&ject ineF)C

Send the actual 7T message, as &ig as %ou likemessage.setontent(FPh4QThis is actual messagePh4QF,

FtexthtmlF )C

Send messageTransport.send(message)CS%stem.out.println(FSent message successfull%....F)C

Hcatch (essagingxception mex) Dmex.printStackTrace()C

HH

H

ompile and run this program to send an 7T e$mail'

K java Send7TmailSent message successfull%....

Send !ttachment in $mail'

7ere is an example to send an email with attachment from %our machine. 7ere it is assumed that %our localhost isconnected to the internet and capa&le enough to send an email.

Aile ame SendAilemail.java

Page 9: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 9/18

import java.util.BCimport javax.mail.BCimport javax.mail.internet.BCimport javax.activation.BC

pu&lic class SendAilemailD

pu&lic static void main(String >? args)D

-ecipient1s email #+ needs to &e mentioned.String to E Fa&cdOgmail.comFC

Sender1s email #+ needs to &e mentionedString from E Fwe&Ogmail.comFC

!ssuming %ou are sending email from localhostString host E FlocalhostFC

@et s%stem properties

"roperties properties E S%stem.get"roperties()C

Setup mail server properties.set"ropert%(Fmail.smtp.hostF, host)C

@et the default Session o&ject.Session session E Session.get+efault#nstance(properties)C

tr%D reate a default imeessage o&ject.imeessage message E new imeessage(session)C

Set Arom' header field of the header.message.setArom(new #nternet!ddress(from))C

Set To' header field of the header.message.add-ecipient(essage.-ecipientT%pe.T0,

new #nternet!ddress(to))C

Set Su&ject' header fieldmessage.setSu&ject(FThis is the Su&ject ineF)C

reate the message part9od%"art message9od%"art E new ime9od%"art()C

Aill the messagemessage9od%"art.setText(FThis is message &od%F)C

reate a multipar messageultipart multipart E new imeultipart()C

Set text message partmultipart.add9od%"art(message9od%"art)C

"art two is attachment

Page 10: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 10/18

message9od%"art E new ime9od%"art()CString filename E Ffile.txtFC+ataSource source E new Aile+ataSource(filename)Cmessage9od%"art.set+ata7andler(new +ata7andler(source))Cmessage9od%"art.setAileame(filename)Cmultipart.add9od%"art(message9od%"art)C

Send the complete message partsmessage.setontent(multipart )C

Send messageTransport.send(message)CS%stem.out.println(FSent message successfull%....F)C

Hcatch (essagingxception mex) Dmex.printStackTrace()C

HH

H

ompile and run this program to send an 7T e$mail'

K java SendAilemailSent message successfull%....

*ser !uthentication "art'

#f it is re3uired to provide user #+ and "assword to the e$mail server for authentication purpose then %ou can set theproperties as follows'

props.set"ropert%(Fmail.userF, Fm%userF)Cprops.set"ropert%(Fmail.passwordF, Fm%pwdF)C

-est of the e$mail sending mechanism would remain as explained a&ove.

APPLET

!n applet is a Java program that runs in a /e& &rowser. !n applet can &e a full% functional Java application &ecausit has the entire Java !"# at its disposal.

There are some important differences &etween an applet and a standalone Java application, including the following

!n applet is a Java class that extends the java.applet.!pplet class.

! main() method is not invoked on an applet, and an applet class will not define main().

!pplets are designed to &e em&edded within an 7T page.

/hen a user views an 7T page that contains an applet, the code for the applet is downloaded to the user1smachine.

! JM is re3uired to view an applet. The JM can &e either a plug$in of the /e& &rowser or a separate runtimeenvironment.

The JM on the user1s machine creates an instance of the applet class and invokes various methods during theapplet1s lifetime.

Page 11: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 11/18

!pplets have strict securit% rules that are enforced &% the /e& &rowser. The securit% of an applet is often referredto as sand&ox securit%, comparing the applet to a child pla%ing in a sand&ox with various rules that must &e followe

0ther classes that the applet needs can &e downloaded in a single Java !rchive (J!-) file.

ife %cle of an !pplet'

Aour methods in the !pplet class give %ou the framework on which %ou &uild an% serious applet'

init' This method is intended for whatever initialiNation is needed for %our applet. #t is called after the param tagsinside the applet tag have &een processed.

start' This method is automaticall% called after the &rowser calls the init method. #t is also called whenever the usreturns to the page containing the applet after having gone off to other pages.

stop' This method is automaticall% called when the user moves off the page on which the applet sits. #t can,therefore, &e called repeatedl% in the same applet.

destro%' This method is onl% called when the &rowser shuts down normall%. 9ecause applets are meant to live onan 7T page, %ou should not normall% leave resources &ehind after a user leaves the page that contains the apple

paint' #nvoked immediatel% after the start() method, and also an% time the applet needs to repaint itself in the&rowser. The paint() method is actuall% inherited from the java.awt.

! F7ello, /orldF !pplet'

The following is a simple applet named 7ello/orld!pplet.java'

import java.applet.BCimport java.awt.BC

pu&lic class 7ello/orld!pplet extends !ppletD

pu&lic void paint (@raphics g)D

g.drawString (F7ello /orldF, 2:, :8)CH

H

These import statements &ring the classes into the scope of our applet class'

java.applet.!pplet.

java.awt.@raphics.

/ithout those import statements, the Java compiler would not recogniNe the classes !pplet and @raphics, which thapplet class refers to.The !pplet !SS'

ver% applet is an extension of the java.applet.!pplet class. The &ase !pplet class provides methods that a derived!pplet class ma% call to o&tain information and services from the &rowser context.

These include methods that do the following'

@et applet parameters

Page 12: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 12/18

@et the network location of the 7T file that contains the applet

@et the network location of the applet class director%

"rint a status message in the &rowser 

Aetch an image

Aetch an audio clip

"la% an audio clip

-esiNe the applet

!dditionall%, the !pplet class provides an interface &% which the viewer or &rowser o&tains information a&out theapplet and controls the applet1s execution. The viewer ma%'

re3uest information a&out the author, version and cop%right of the applet

re3uest a description of the parameters the applet recogniNes

initialiNe the applet

destro% the applet

start the applet1s execution

stop the applet1s execution

The !pplet class provides default implementations of each of these methods. Those implementations ma% &eoverridden as necessar%.

The F7ello, /orldF applet is complete as it stands. The onl% method overridden is the paint method.#nvoking an !pplet'

!n applet ma% &e invoked &% em&edding directives in an 7T file and viewing the file through an applet viewerJava$ena&led &rowser.

The PappletQ tag is the &asis for em&edding an applet in an 7T file. 9elow is an example that invokes the F7ell/orldF applet'

PhtmlQ

PtitleQThe 7ello, /orld !ppletPtitleQPhrQPapplet codeEF7ello/orld!pplet.classF widthEF528F heightEF428FQ#f %our &rowser was Java$ena&led, a F7ello, /orldFmessage would appear here.PappletQPhrQPhtmlQ

9ased on the a&ove examples, here is the live applet example' !pplet xample.

ote' Lou can refer to 7T !pplet Tag to understand more a&out calling applet from 7T.

Page 13: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 13/18

The code attri&ute of the PappletQ tag is re3uired. #t specifies the !pplet class to run. /idth and height are alsore3uired to specif% the initial siNe of the panel in which an applet runs. The applet directive must &e closed with aPappletQ tag.

#f an applet takes parameters, values ma% &e passed for the parameters &% adding PparamQ tags &etween PappletQ aPappletQ. The &rowser ignores text and other tags &etween the applet tags.

on$Java$ena&led &rowsers do not process PappletQ and PappletQ. Therefore, an%thing that appears &etween thetags, not related to the applet, is visi&le in non$Java$ena&led &rowsers.

The viewer or &rowser looks for the compiled Java code at the location of the document. To specif% otherwise, usethe code&ase attri&ute of the PappletQ tag as shown'

Papplet code&aseEFhttp'amrood.comappletsFcodeEF7ello/orld!pplet.classF widthEF528F heightEF428FQ

#f an applet resides in a package other than the default, the holding package must &e specified in the code attri&uteusing the period character (.) to separate packageclass components. Aor example'

Papplet codeEFm%package.su&package.Test!pplet.classFwidthEF528F heightEF428FQ

@etting !pplet "arameters'

The following example demonstrates how to make an applet respond to setup parameters specified in the documentThis applet displa%s a checker&oard pattern of &lack and a second color.

The second color and the siNe of each s3uare ma% &e specified as parameters to the applet within the document.

hecker!pplet gets its parameters in the init() method. #t ma% also get its parameters in the paint() method. 7owevgetting the values and saving the settings once at the start of the applet, instead of at ever% refresh, is convenient anefficient.

The applet viewer or &rowser calls the init() method of each applet it runs. The viewer calls init() once, immediatelafter loading the applet. (!pplet.init() is implemented to do nothing.) 0verride the default implementation to insertcustom initialiNation code.

The !pplet.get"arameter() method fetches a parameter given the parameter1s name (the value of a parameter isalwa%s a string). #f the value is numeric or other non$character data, the string must &e parsed.

The following is a skeleton of hecker!pplet.java'

import java.applet.BC

import java.awt.BCpu&lic class hecker!pplet extends !ppletD

int s3uareSiNe E :8C initialiNed to default siNepu&lic void init () DHprivate void parseS3uareSiNe (String param) DHprivate olor parseolor (String param) DHpu&lic void paint (@raphics g) DH

H

7ere are hecker!pplet1s init() and private parseS3uareSiNe() methods'

pu&lic void init ()

Page 14: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 14/18

DString s3uareSiNe"aram E get"arameter (Fs3uareSiNeF)CparseS3uareSiNe (s3uareSiNe"aram)CString color"aram E get"arameter (FcolorF)Color fg E parseolor (color"aram)Cset9ackground (olor.&lack)CsetAoreground (fg)C

Hprivate void parseS3uareSiNe (String param)D

if (param EE null) returnCtr% D

s3uareSiNe E #nteger.parse#nt (param)CHcatch (xception e) D et default value remain

HH

The applet calls parseS3uareSiNe() to parse the s3uareSiNe parameter. parseS3uareSiNe() calls the li&rar% method#nteger.parse#nt(), which parses a string and returns an integer. #nteger.parse#nt() throws an exception whenever its

argument is invalid.

Therefore, parseS3uareSiNe() catches exceptions, rather than allowing the applet to fail on &ad input.

The applet calls parseolor() to parse the color parameter into a olor value. parseolor() does a series of stringcomparisons to match the parameter value to the name of a predefined color. Lou need to implement these methodsmake this applet works.Specif%ing !pplet "arameters'

The following is an example of an 7T file with a hecker!pplet em&edded in it. The 7T file specifies &othparameters to the applet &% means of the PparamQ tag.

PhtmlQPtitleQhecker&oard !ppletPtitleQPhrQPapplet codeEFhecker!pplet.classF widthEF6=8F heightEF528FQPparam nameEFcolorF valueEF&lueFQPparam nameEFs3uaresiNeF valueEF58FQPappletQPhrQPhtmlQ

ote' "arameter names are not case sensitive.!pplication onversion to !pplets'

#t is eas% to convert a graphical Java application (that is, an application that uses the !/T and that %ou can start withe java program launcher) into an applet that %ou can em&ed in a we& page.

7ere are the specific steps for converting an application to an applet.

ake an 7T page with the appropriate tag to load the applet code.

Suppl% a su&class of the J!pplet class. ake this class pu&lic. 0therwise, the applet cannot &e loaded.

liminate the main method in the application. +o not construct a frame window for the application. Lour

Page 15: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 15/18

application will &e displa%ed inside the &rowser.

ove an% initialiNation code from the frame window constructor to the init method of the applet. Lou don1t needexplicitl% construct the applet o&ject.the &rowser instantiates it for %ou and calls the init method.

-emove the call to setSiNeC for applets, siNing is done with the width and height parameters in the 7T file.

-emove the call to set+efaultlose0peration. !n applet cannot &e closedC it terminates when the &rowser exits.

#f the application calls setTitle, eliminate the call to the method. !pplets cannot have title &ars. (Lou can, of cour

title the we& page itself, using the 7T title tag.)

+on1t call setMisi&le(true). The applet is displa%ed automaticall%.

vent 7andling'

!pplets inherit a group of event$handling methods from the ontainer class. The ontainer class defines severalmethods, such as processRe%vent and processousevent, for handling particular t%pes of events, and then onecatch$all method called processvent.

#n order to react an event, an applet must override the appropriate event$specific method.

import java.awt.event.ouseistenerCimport java.awt.event.ouseventCimport java.applet.!ppletCimport java.awt.@raphicsC

pu&lic class xamplevent7andling extends !ppletimplements ouseistener D

String9uffer str9ufferC

pu&lic void init() Daddouseistener(this)Cstr9uffer E new String9uffer()C

add#tem(FinitialiNing the apple F)CH

pu&lic void start() Dadd#tem(Fstarting the applet F)C

H

pu&lic void stop() D

add#tem(Fstopping the applet F)CH

pu&lic void destro%() Dadd#tem(Funloading the appletF)C

H

void add#tem(String word) DS%stem.out.println(word)Cstr9uffer.append(word)Crepaint()C

H

Page 16: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 16/18

pu&lic void paint(@raphics g) D+raw a -ectangle around the applet1s displa% area.

g.draw-ect(8, 8,get/idth() $ 4,

  get7eight() $ 4)C

displa% the string inside the rectangle.g.drawString(str9uffer.toString(), 48, 28)C

H

 pu&lic void mousentered(ousevent event) DHpu&lic void mousexited(ousevent event) DHpu&lic void mouse"ressed(ousevent event) DHpu&lic void mouse-eleased(ousevent event) DH

pu&lic void mouselicked(ousevent event) D

add#tem(Fmouse clicked F)CH

H

ow, let us call this applet as follows'

PhtmlQPtitleQvent 7andlingPtitleQPhrQPapplet codeEFxamplevent7andling.classFwidthEF588F heightEF588FQ

PappletQPhrQPhtmlQ

#nitiall%, the applet will displa% FinitialiNing the applet. Starting the applet.F Then once %ou click inside the rectanglFmouse clickedF will &e displa%ed as well.

9ased on the a&ove examples, here is the live applet example' !pplet xample.+ispla%ing #mages'

!n applet can displa% images of the format @#A, J"@, 9", and others. To displa% an image within the applet, %o

use the draw#mage() method found in the java.awt.@raphics class.

Aollowing is the example showing all the steps to show images'

import java.applet.BCimport java.awt.BCimport java.net.BCpu&lic class #mage+emo extends !ppletDprivate #mage imageCprivate !ppletontext contextC

pu&lic void init()D

Page 17: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 17/18

context E this.get!ppletontext()CString image*- E this.get"arameter(FimageF)Cif(image*- EE null)D

image*- E Fjava.jpgFCHtr%D

*- url E new *-(this.get+ocument9ase(), image*-)Cimage E context.get#mage(url)C

Hcatch(alformed*-xception e)D

e.printStackTrace()C +ispla% in &rowser status &ar context.showStatus(Fould not load imageF)C

HHpu&lic void paint(@raphics g)D

context.showStatus(F+ispla%ing imageF)Cg.draw#mage(image, 8, 8, 288, =6, null)C

g.drawString(Fwww.javalicense.comF, 5:, 488)CH

H

ow, let us call this applet as follows'

PhtmlQPtitleQThe #mage+emo appletPtitleQPhrQPapplet codeEF#mage+emo.classF widthEF588F heightEF288FQPparam nameEFimageF valueEFjava.jpgFQ

PappletQPhrQPhtmlQ

9ased on the a&ove examples, here is the live applet example' !pplet xample."la%ing !udio'

!n applet can pla% an audio file represented &% the !udiolip interface in the java.applet package. The !udiolipinterface has three methods, including'

pu&lic void pla%()' "la%s the audio clip one time, from the &eginning.

pu&lic void loop()' auses the audio clip to repla% continuall%.

pu&lic void stop()' Stops pla%ing the audio clip.

To o&tain an !udiolip o&ject, %ou must invoke the get!udiolip() method of the !pplet class. The get!udiolip(method returns immediatel%, whether or not the *- resolves to an actual audio file. The audio file is notdownloaded until an attempt is made to pla% the audio clip.

Aollowing is the example showing all the steps to pla% an audio'

import java.applet.BCimport java.awt.BC

Page 18: Networking Applet

8/10/2019 Networking Applet

http://slidepdf.com/reader/full/networking-applet 18/18

import java.net.BCpu&lic class !udio+emo extends !ppletD

private !udiolip clipCprivate !ppletontext contextCpu&lic void init()D

context E this.get!ppletontext()CString audio*- E this.get"arameter(FaudioF)Cif(audio*- EE null)

Daudio*- E Fdefault.auFC

Htr%D

*- url E new *-(this.get+ocument9ase(), audio*-)Cclip E context.get!udiolip(url)C

Hcatch(alformed*-xception e)D

e.printStackTrace()Ccontext.showStatus(Fould not load audio fileF)C

HHpu&lic void start()D

if(clip E null)D

clip.loop()CH

Hpu&lic void stop()D

if(clip E null)D

clip.stop()CH

HH

ow, let us call this applet as follows'

PhtmlQPtitleQThe #mage+emo appletPtitleQ

PhrQPapplet codeEF#mage+emo.classF widthEF8F heightEF8FQPparam nameEFaudioF valueEFtest.wavFQPappletQPhrQPhtmlQ

Lou can use %our test.wav at %our " to test the a&ove example.