Internet Technologies complete notes
Internet Technologies
Unit 1
Introduction: Overview, Network of Networks, Intranet, Extranet and Internet. World Wide Web, Domain and Sub domain, Address Resolution, DNS, Telnet, FTP, HTTP. Review of TCP/IP: Features, Segment, Three-Way Handshaking, Flow Control, Error Control, Congestion control.
Introduction to Internet Technologies
The Technologies which are involved to collect various types of information and for communication all over the world is called as internet technologies. Technology is expressing skill of a human mechanism to achieve a thing for example architecture is a technology to build an efficient house / apartment / avenue. Many small network technologies are used to build an efficient networking model.
Network – network is the connection between two or more independent computer machines to send and receive data. The connection is wired or wireless. The network infrastructure setup may be physically or logically.
Computer B |
Computer C |
Computer D |
Computer A |
Network of Network:
Internet is called as network of networks because internet is the global network of all kind of networks from all over the world such as public, private, academic, business and government etc. Networks are connected by cables and telephone lines.
Network devices
Modem – is a computer hardware device used to modulate and demodulate the data signals from and to suitable transmission media ie converts from digital data to analog data and analog data to digital data. For example modem converts analog signal from telephone line into digital data and transmits to the computer system connected in the network as well as converts digital data from computer system into analog signals and transmits to the telephone line for transmission.
NIC – Network Interface Card is used to provide network connection to the computer system just like the SIM card providing communication service to the mobile phone.
Router - is a networking device used to forward data packets between computer networks. The three main functions of router are
1. Connecting different computer networks
2. Finding shortest path
3. Joins different networks with different network addresses together.
Switch – is a networking devices used to connect multiple devices to form a network to transmit and receive data packets.
Transmission Media
LAN – Local Area Network is the collection computer devices connected together to share some resources like printer files etc., within a physical location such a building , office or any enterprise.
MAN – Metropolitan Area Network is the computer network larger than LAN and smaller than WAN, it covers a small geographical area which can be bounded within a city. For example an enterprise which is having multiple branches in a city can be connected together in a network is said to be Metropolitan Area Network MAN
WAN – Wide Area Network is the global network of networks can also be called as internet. Collection of all LAN,MAN, wired, wireless, public , private … networks is called as WAN. For example a bank including its branch offices and ATM centers.
INTRANET – intranet is a private network for an enterprise to share company information securely and work on its resources among their employees. For example bank network bank employees.
EXTRANET – same as intranet it is a private network of an enterprise which gives additional access authorities for its partners or customers. For example mobile banking or net banking gives permission for their customers and share holders to access their accounts.
Internet
The internet is the very biggest network which connects all over the world. The internet is the worldly network which accessed by the www. The internet is the network of networks of many electronic devices. It connects network of government organizations, private organizations, schools, universities, colleges, banks and all other organizations.
World wide web
World wide web is the centralized document system. Collection of websites, website is the collection of web pages, where web page is collection of text, audio, video, events, controls and links.
Web server
Web browser – application program runs on client machine
HTML – Hyper Text Markup Language used to design web pages
HTTP – Hyper Text Transfer Protocol used to format request and response messages
Domain and Sub domain
Domain name is the address name of a website. It points the specific address on the web. It stands after @. For example http://www.mail@google.com
http - protocol
:// format
www – world wide web – Sub Domain comes before second level domain
mail – Second Level Domain – portion part of the domain (website)
google – domain – is the address of website
com– Top Level Domain , some of the TLD’s are .com – commercial,.edu – education, .gov – government org…
Address Resolution
DNS
Telnet
FTP
HTTP
Overview of TCP/IP
Features
Segments
Three way handshake method
A three-way handshake is a method used in a TCP/IP network to create a connection between a local host/client and server.
It is a three-step method designed to allow both communicating ends to initiate and negotiate the parameters of the network TCP socket connection at the same time before data such as HTTP and SSH is transmitted.
Multiple TCP socket connections can be transmitted in both directions simultaneously. A three-way handshake is also known as a TCP handshake or SYN-SYN-ACK, and requires both the client and server to exchange SYN (synchronization) and ACK (acknowledgment) packets before actual data communication begins.
In fact, its name originates from the three messages transmitted by TCP before a session between the two ends is initiated.
Step 1 - Connection established – sender send a SYN packet which contains sequence number(X)
Step 2 – Receiver send SYN/ACK back to the sender SYN(sequence no X+1) and ACK(acknowledgement receipt ack number Y)
Step 3 – Sender keeps the SYN and send ACK(Y+1) to the Receiver
Flow Control
TCP flow control was designed to manage the data transmission (flow) ie to retain the amount of data between the user and server. It ensures the synchronization between the sender and receiver
Types
Stop and wait protocol
In stop and wait protocol, Sender send a data packet and wait for the acknowledgement from the receiver, once it received ack then it send the next packet and so on.
Sliding window protocol
In sliding window protocol, when connection established two buffers created at sender and receiver end and called as sender window and receiver window. When sender sends data to the receiver, receiver send ack for receiving data and balance available space in buffer. If available space is not enough for next data frame then sender stop transferring data and wait for ack of free space from receiver. After receiving free space message from receiver then sender starts to send data.
Error Control
Error control mechanism is used to find corrupted messages, missed messages, out of order messages and duplicated messages.
Checksum error control – for corrupted messages
Acknowledgement – to find missed messages
Retransmission – for corrupted data, lost data, out – of – order data and duplicated messages.
Retransmission Time Out RTO - RTO is dynamic in TCP and is updated based on the round-trip time (RTT) of segments. An RTI is the time needed for a segment to reach a destination and for an acknowledgment to be received.
Retransmission after 3 duplicate ACK - One segment is lost and the receiver receives so many out-of-order segments that they cannot be saved, to alleviate this situation, most implementations today follow the three-duplicate-ACKs rule and retransmit the missing segment immediately.
Congestion Control - Congestion control refers to the techniques used to control or prevent congestion. Congestion control techniques can be broadly classified into two categories.
Open Loop congestion control – policies applied before congestion happened
Retransmission Policy -
Window Policy
Discarding policy
ACK policy
Admission Policy
Closed Loop congestion control – techniques applied to treat congestion happened
Back pressure – node stops receiving messages and send back messages to sender
Choke packet technique – choke packet is send to source by a node (router) to inform about congestion.
Implicit signaling – when sender observes congestion, it send a alert message about congestion
Explicit signaling – when congestion observes - forward and backward signaling, forward signal send alert message to receiver. Backward signaling send alert message to sender to slow down of sending messages
Questions
One mark
1. Network of Network is called as _____________(internet)
2. Choke packet is send to source by a node (router) to inform about ______________(Congestion)
3. A three-way handshake is a method used in a _____________ network to create a connection between a local host/client and server.(TCP/IP)
4. All type of media files can be transferred in telnet - false
5. In sliding window protocol two buffers created before transmission – true
Two marks
1. Define web browser.
2. List out the basic components of internet.
3. What is FTP?
4. What is meant by Domain and sub domain in address resolution?
5. How can you define three – way – handshake methods?
Five marks
1. Explain the following with suitable diagrams i) LAN ii) WAN iii)MAN
2. Describe Intranet and Extranet in detail.
3. Discuss in detail about Overview of TCP/IP.
4. Explain in detail – three types of control mechanism in TCP.
5. Explain Address Resolution.
6. Describe i)Telnet ii) FTP iii) HTTP.
Unit – II – IP Datagram
IP Datagram, IPv4 and IPv6. IP Subnetting and addressing: Classful and Classless Addressing, Subnetting. NAT, IP masquerading, IP tables. Internet Routing Protocol: Routing -Intra and Inter Domain Routing, Unicast and Multicast Routing, Broadcast. Electronic Mail: POP3, SMTP.
IP Datagram
What is a IP datagram?
IP datagram contain whatever data is being sent which associated with IP headers, while IP packets are used to get the datagram to the destination system as specified in the IP headers. The IP datagram is constructed by the Network Layer (Layer 3) of the OSI model. This layer is responsible for routing data packets between different networks and ensuring that they reach their intended destination successfully. "Datagram" is a segment of data sent over a packet-switched network. A datagram contains enough information to be routed from its source to its destination. By this definition, an IP packet and IP datagram both are same.
Versions – IPV4 and IPV6
IP stands for Internet
Protocol and v4 stands for Version Four
(IPv4). IPv4 was the primary version brought into action for production within
the ARPANET in 1983.
IP version four addresses are 32-bit integers which will be expressed in
decimal notation.
Example- 192.0.2.126 could be an IPv4 address. It contains source address
, destination address , network address and error handling mechanism along with
data.
IPV6 –
IPv6 was the communication protocol and developed by the Internet Engineering Task Force (IETF) to deal with the long-anticipated problem of IPv4 address exhaustion, and was intended to replace IPv4. In December 1998, IPv6 became a Draft Standard for the IETF, which subsequently ratified it as an Internet Standard on 14 July 2017. It has 128 bit address space.
IPV4 and IPV6
IPv4 |
IPv6 |
IPv4 has a 32-bit address length |
IPv6 has a 128-bit address length |
It Supports Manual and DHCP address configuration |
It supports Auto and renumbering address configuration |
In IPv4 end to end, connection integrity is Unachievable |
In IPv6 end-to-end, connection integrity is Achievable |
It can generate 4.29×109 address space |
The address space of IPv6 is quite large it can produce 3.4×1038 address space |
The Security feature is dependent on the application |
IPSEC is an inbuilt security feature in the IPv6 protocol |
Address representation of IPv4 is in decimal |
Address Representation of IPv6 is in hexadecimal |
Fragmentation performed by Sender and forwarding routers |
In IPv6 fragmentation is performed only by the sender |
In IPv4 Packet flow identification is not available |
In IPv6 packet flow identification are Available and uses the flow label field in the header |
In IPv4 checksum field is available |
In IPv6 checksum field is not available |
It has a broadcast Message Transmission Scheme |
In IPv6 multicast and anycast message transmission scheme is available |
In IPv4 Encryption and Authentication facility not provided |
In IPv6
Encryption and Authentication are provided |
IPv4 has a header of 20-60 bytes. |
IPv6 has a
header of 40 bytes fixed |
IPv4 can be converted to IPv6 |
Not all IPv6 can be converted to IPv4 |
IPv4 consists of 4 fields which are separated by addresses dot (.) |
IPv6 consists of 8 fields, which are separated by a colon (:) |
IPv4’s IP addresses are divided into five different classes. Class A , Class B, Class C, Class Da , Class E. |
IPv6 does not have any classes of the IP address. |
IPv4 supports VLSM(Variable Length subnet mask). |
IPv6 does not support VLSM. |
Example of IPv4: 66.94.29.13 |
Example of IPv6: 2001:0000:3238:DFE1:0063:0000:0000:FEFB |
Masquerade is the type masking technique i.e. pretend to be act as someone else to gain access of a system or data.
Types
Username password masquerade – forged or stolen credentials for login
IP address masquerade – forged or spoof ip address
Website masquerade – creates fake website which resembling original website
Email or message masquerade – sending false mail or message to get sensitive information from the
Unit – 3 – HTML
Introduction, Editors, Elements, Attributes, Heading, Paragraph. Formatting, Link, Head, Table, List, Block, Layout, CSS. Form, Iframe, Colors, Color name, Color value. Image Maps: map, area, attributes ofimage area. Extensible Markup Language (XML): Introduction, Tree, Syntax, Elements, Attributes, Validation, Viewing. XHTML in brief. CGI Scripts: Introduction, Environment Variable, GET and POST Methods
HTML
Planning for designing web pages:
Breaking Up Your Content into Main Topics
With your goals in mind, try to organize your content into main topics or sections, chunk ingrelated information together under a single topic.
Ideas for Organization and Navigation
At this point, you should have a good idea of what you want to talk about as well as a list of topics. The next step is to actually start structuring the information you have into a set of web pages. Before you do that, however, consider some standard structures that have been used in other help systems and online tools. This section describes some of these structures, their various features, some important considerations, including the following Model and Structure of a Website:
You need to know what the following terms mean and how they apply to the body of
Work you're developing for the Web:
Website:A collection of one or more webpages linked together in a meaningful way that,as a whole, describes a body of information or creates an overall effect.
Webserver: A computer on the Internet or an intranet that delivers Webpages and other files in response to browser requests.
Webpage:A single document on a website, usually consisting of an HTML document and any items that are displayed within that document such as in line images.
Home page: The entry page for a website, which can link to additional pages on the same website or pages on other sites.
Developingwebsites:
Designing a website, like designing a book outline, a building plan, or a painting, cansometimes be a complex and involved process. Having a plan before you begin can helpyou keep the details straight and help you develop the finished product with fewer falsestarts.Today, you learned how to put together a simple plan and structure for creating a set of webpages, including the following:
• Deciding what sort of content to present
• Coming up with a set of goals for that content
• Deciding on a set of topics
• Organizing and story boarding the website
Basic HTML:HTML stands for Hypertext Markup Language. The idea here is that mostdocuments have common elements for example, titles, paragraphs, and lists. Before youstart writing, therefore, you can identify and define the set of elements in that documentandgivethemappropriatenames.
How MarkupWorks
HTML is a markup language. Writing in a markup language means that you start with thetext of your page and add special tags around words and paragraphs. The tags indicate thedifferent parts of the page and produce different effects in the browser. HTML has adefined set of tags you can use. You can't make up your own tags to create new styles orfeatures.
WhatHTMLFilesLookLike
Pages written in HTML are plain text files (ASCII), which means that they contain noplatform-orprogram-specificinformation.Anyeditorthatsupportstextcanreadthem.HTML filescontainthefollowing:
• Thetext ofthepageitself
• HTMLtagsthatindicatepageelements, structure,formatting,andhypertextlinksto
otherpagesortoincludedmedia. MostHTMLtagslooksomethinglikethefollowing:
<thetagname>affectedtext</thetagname>
Thetagnameitself(here,thetagname)isenclosedinbrackets(<>).HTMLtagsgenerally have abeginning and an ending tag surrounding the textthey affect. Thebeginning tag "turns on" a feature (such as headings, bold, and so on), and the ending tagturns it off. Closing tags have the tag name preceded by a slash (/). The opening tag (forexample,<p>forparagraphs)andclosingtag(forexample,</p>forparagraphs)compose what is officially called an HTML element.
Text Formatting and HTML
When an HTML page is parsed by a browser, any formatting you might have done by hand that is, any extra spaces, tabs, returns, and so on is ignored. The only thing that’ specifies formatting in an HTML page is an HTML tag. If you spend hours carefully editing a plain text file to have nicely formatted paragraphs and columns of numbers but don't include any tags, when a web browser loads the page, all the text will flow into one paragraph. All your work will have been in vain.
The advantage of having all white space (spaces, tabs, returns) ignored is that you can put your tags wherever you want. The following examples all produce the same output. Try them!
<h1>Ifmusicbethefoodoflove,playon.</h1>
<h1>
Ifmusicbethefoodoflove,playon.
</h1>
<h1>
Ifmusicbethe foodoflove,playon.</h1>
<h1>Ifmusicbethefoodoflove,playon.</h1>
Structuring Your HTMLTheDOCTYPEIdentifier
A
\lthoughit'snotapagestructuretag,theXHTML1.0recommendationincludesoneadditional requirement for your web pages. The first line of each page must include aDOCTYPEidentifierthatdefinestheXHTML1.0versiontowhichyourpageconforms,andthedocumenttypedefinition(DTD)thatdefinesthespecification.Thisisfollowedbythe<html>,<head>,and<body>tags.Inthefollowingexample,theXHTML1.0Strictdocument typeappearsbeforethepagestructuretags:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/strict.dtd">
<html>
<head>
<title>PageTitle</title>
</head>
<body>
...yourpagecontent...
</body>
</html>
ThreetypesofHTML4.01documenttypesarespecifiedintheXHTML1.0specification:
Strict,Transitional,andFrameset.
The<html>Tag
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
...yourpage...
</html>
The<head>Tag
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<title>ThisistheTitle.Itwillbeexplainedlateron</title>
</head>
...yourpage...
</html>
The<body>Tag
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<title>ThisistheTitle.Itwillbeexplainedlateron</title>
</head>
<body>
...yourpage...
</body>
</html>
TheTitle
EachHTMLpageneedsatitletoindicatewhatthepagedescribes.Itappearsinthetitlebarofthebrowser whenpeopleviewthewebpage.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html>
<head>
<title>TheLion,TheWitch,andtheWardrobe</title>
</head>
<body>
...yourpage...
</body>
</html>
Headings
Headingsareusedtoaddtitles tosectionsofa page.HTMLdefinessixlevelsofheadings.
Headingtagslooklikethefollowing:
<h1>Movies</h1>
<h2>Action/Adventure</h2>
<h3>Caper</h3>
<h3>Sports</h3>
<h3>Thriller</h3>
<h3>War</h3>
<h2>Comedy</h2>
<h3>RomanticComedy</h3>
<h3>Slapstick</h3>
<h2>Drama</h2>
<h3>BuddyMovies</h3>
<h3>Mystery</h3>
<h3>Romance</h3>
<h2>Horror</h2>
Paragraphs
AsoftheHTML4.01standard,paragraphtagsaretwo-sided(<p>...</p>),and<p>indicates the beginning of the paragraph. The closing tag is no longer optional, so ratherthanusing<p>toindicatewhereoneparagraphendsandanotherbegins,youencloseeachparagraphwithina<p> tag.
Input
<p>The dragon fell to the ground, releasing an anguished cry and seething in pain. Thethrust of Enigern's sword proved fatal as the dragon breathed its last breath. Now Enigernwas freetoreleaseLadyAelfleada fromher imprisonmentinthedragon'slair.
</p>
Image:
ImagesdisplayedontheWebshouldbeconvertedtooneoftheformatssupportedbymost browsers: GIF, JPEG, or PNG. GIF and JPEG are the popular standards, and everygraphical browser supports them. PNG is a newer image format that was created inresponsetosomepatentissueswiththeGIF format.
Themostimportantattributeofthe<img>tagissrc,whichistheURLoftheimageyouwanttoinclude.Pathstoimagesarederivedinthesamewayasthepathsinthehrefattribute of links. So, to point to a GIF file named image.gif in the same directory as theHTML document,youcanusethefollowingHTMLtag:
<imgsrc="image.gif"/>
Input:
<p><imgsrc="house.jpg"alt="HouseofTerror"/></p>
<h1>WelcometoTheHalloweenHouseofTerror!!</h1>
Output:
Links:
TocreatealinkinanHTMLpage,youusetheHTMLlinktag<a>...</a>.The<a>tagofteniscalledananchortagbecauseitalsocan beusedtocreateanchorsforlinks.
Input
Gobackto<ahref="menu.html">MainMenu</a>
Lists:
HTML4.01definesthesethreetypesoflists:
• Numberedororderedlists,whicharetypicallylabeledwithnumbers
• Bulletedorunorderedlists,whicharetypicallylabeledwithbulletsorsomeothersymbol
• Glossarylists,inwhicheachiteminthelisthasatermandadefinitionforthatterm,arrangedsothatthetermissomehowhighlightedordrawnout fromthetext
ListTags
Allthelisttagshavethefollowingcommonelements:
• Theentirelistissurroundedbytheappropriateopeningandclosingtagforthetype
oflist(forexample,<ul>and</ul>forunorderedlists,or<ol>and</ol>fororderedlists).
• Eachlistitemwithinthelisthasitsowntag:
<dt>and<dd>fortheglossarylists,and<li>for alltheotherlists.
Input
• <p>InstallingYourNewOperatingSystem</p>
• <ol>
• <li>InserttheCD-ROMinto yourCD-ROMdrive.</li>
• <li>ChooseRUN.</li>
• <li>Enter the drive letter of your CD-ROM (example: D:\), followed bySETUP.EXE.</li>
• <li>Followthepromptsinthesetupprogram.</li>
• <li>Rebootyourcomputerafterallfilesareinstalled.</li>
• <li>Crossyourfingers.</li>
• </ol>
CustomizingOrderedLists
You can customize ordered lists in two main ways: how they're numbered and the numberwith which the list starts. HTML 3.2 provides the type attribute that can take one of fivevaluestodefinewhichtypeofnumberingtouseon thelist:
• "1" Specifies that standard Arabic numerals should be used to number the list (thatis,1,2,3,4,andsoon)
• "a" Specifies that lowercase letters should be used to number the list (that is, a, b, c,d,andsoon)
• "A" Specifies that uppercase letters should be used to number the list (that is, A, B,C,D,andsoon)
• "i"SpecifiesthatlowercaseRomannumeralsshouldbeusedtonumberthelist(thatis,i,ii,iii,iv,andsoon)
• "I"Specifiesthat uppercaseRomannumeralsshouldbeusedtonumberthelist(thatis,I,II,III,IV,andsoon)
Youcanspecifytypesofnumberinginthe<ol>tag,asfollows:<oltype="a">.Bydefaulttype="1"isassumed.
Input
<p>TheDaysoftheWeekinFrench:</p>
<oltype="I">
<li>Lundi</li>
<li>Mardi</li>
<li>Mercredi</li>
<li>Jeudi</li>
<li>Vendredi</li>
<li>Samedi</li>
<li>Dimanche</li>
</ol>
Input
<p>TheLastSixMonthsoftheYear(andtheBeginningoftheNextYear):</p>
<oltype="I"start="7">
<li>July</li>
<li>August</li>
<li>September</li>
<li>October</li>
<li>November</li>
<li>December</li>
<litype="1">January</li>
</ol>
Tables:
TableParts
BeforegettingintotheactualHTMLcodetocreateatable,let'slookatthefollowingterms sothatwebothknowwhat we'retalkingabout:
• Thecaptionindicateswhatthetableisabout:forexample,"VotingStatistics"or"ToyDistributionPer Room"Captionsareoptional.
• Thetableheadingslabeltherows,columns,orboth.Usuallythey'reinanemphasizedfontthat'sdifferentfromtherestofthetable.They'reoptional.
• Tablecellsaretheindividualsquaresinthetable.Acellcancontainnormaltabledataoratableheading.
• Table data is the values in the table itself. The combination of the table headings andtabledatamakesupthesumofthetable.
The<table>Element
ThetocreateatableinHTML,youuse<table>...</table>elementtoenclosethecodeforanoptionalcaption,andthenaddthecontentsofthetableitself:
<table>
...tablecaption(optional)andcontents...
</table>
RowsandCells
Thecellswithineachrowarecreatedusingone oftwoelements:
• <th>...</th> elements are used for heading cells. Generally, browsers center the contentsofa<th> cell andrender anytext inthecell inboldface.
• <td>...</td>elementsareusedfordatacells. TDstandsfortabledata.
Input
<tr>
<th>Name</th>
<td>Alison</td>
<td>Tom</td>
<td>Susan</td>
</tr>
<tr>
<th>Height</th>
<td>5'4"</td>
<td>6'0"</td>
<td>5'1"</td>
</tr>
<tr>
<th>Weight</th>
<td>140</td>
<td>165</td>
<td>97</td>
</tr>
<tr>
<th>EyeColor</th>
<td>Blue</td>
<td>Blue</td>
<td>Brown</td>
</tr>
SettingTableWidths
Tomakeatableaswideasthebrowserwindow,youaddthewidthattributetothetable,asshowninthefollowinglineof code:
<tableborder="1"width="100%">
ChangingTableBorders
Youcanchangethewidthoftheborderdrawnaroundthetable.Ifborderhasanumericvalue,theborderaroundtheoutsideofthetableisdrawnwiththatpixelwidth.Thedefault is border="1". border="0" suppresses the border, just as if you had omitted theborderattributealtogether.
Input
<tableborder="10"width="100%">
CellPadding
Thecellpaddingattributedefinestheamountofspacebetweentheedgesofthecellsand thecontentinsideacell.
Input
<tablecellpadding="10"border="1">
CellSpacing
Cell spacing is similar to cell padding except that it affects the amount of space betweencells that is, the widthof thespace between the inner and outer lines thatmake up thetableborder.
Input
<tablecellpadding="10"border="4"cellspacing="8">
SpanningMultipleRowsorColumns
Thetablesyou'vecreateduptothispointallhadonevaluepercellortheoccasionalempty cell. You also can create cellsthat span multiple rows or columns within the table.Those spanned cells then can hold headings that have subheadings in the next row orcolumnoryoucancreateotherspecial effectswithinthetablelayout.
Input
<html>
<head>
<title>RowandColumnSpans</title>
</head>
<body>
<tableborder="1"summary="spanexample">
<tr>
<thcolspan="2">Gender</th>
</tr>
<tr>
<th>Male</th>
<th>Female</th>
</tr>
<tr>
<td>15</td>
<td>23</td>
</tr>
</table>
</body>
</html>
Forms:
Usingthe<form>Tag
To accept input from a user, you must wrap all of your input fields inside a <form> tag.The purpose of the <form> tag is to indicate where and how the user's input should besent. First, let's look at how the <form> tag affects page layout. Forms are block-levelelements.
Input
<p>Pleaseenteryourusername<form><input/>andpassword<input/></form>tologin.</p>
The two most commonly used attributes of the <form> tag are action and method. Both oftheseattributesareoptional.Thefollowingexampleshowshowthe<form>tagistypicallyused:
<formaction="someaction"method="getorpost">content,formcontrols,andotherHTML elements
</form>
action specifies the URL to which the form is submitted. Again, remember that for theform to be submitted successfully, the script must be in the exact location you specify andmustworkproperly.
The method attribute supports two values: get or post. The method indicates how the formdata should be packaged in the request that's sent back to the server. The get methodappendstheformdatatotheURLintherequest.
CreatingTextControls
Text controls enable you to gather information from a user in small quantities. Thiscontrol type creates a single-line text input field in which users can type information, suchastheir nameor asearchterm.
Input
<p>Enteryourpet'sname:
<inputtype="text"name="petname"/></p>
CreatingPasswordControls
Thepasswordandtextfieldtypesareidenticalineverywayexceptthatthedataenteredin a password field is masked so that someone looking over the shoulder of the personenteringinformationcan'tseethevaluethat wastypedintothefield.
Input
<p>Enteryourpassword:<inputtype="password"name="userpassword"size="8"maxlength="8"/></p>
CreatingSubmitButtons
Submitbuttonsareusedtoindicatethattheuserisfinishedfillingouttheform.Settingthetypeattributeoftheformtosubmitplacesasubmitbuttononthepagewiththe
defaultlabeldeterminedbythebrowser,usuallySubmitQuery.Tochangethebuttontext,usethe valueattributeandenteryour ownlabel,as follows:
<inputtype="submit"value="SendFormData"/>
CreatingResetButtons
Resetbuttonsset all the form controls to theirdefault values. These are thevaluesincluded inthe valueattributes of eachfieldin theform (or inthecaseof selectablefields, the values that are preselected). As with the Submit button, you can change thelabelofaResetbuttontooneofyourownchoosingbyusingthevalue attribute,likethis:
<inputtype="reset"value="ClearForm"/>
CreatingCheckBoxControls
Check boxes are fields that can be set to two states: on and off. To create a check box, setthe input tag's type attribute to checkbox. The name attribute is also required, as shown inthefollowingexample:
Input
<p>ChecktoreceiveSPAMemail<inputtype="checkbox"name="spam"/></p>
CreatingRadioButtons
Radiobuttons,whichgenerallyappearingroups,aredesignedsothatwhenonebuttoninthegroupisselected,theotherbuttonsinthegroupareautomaticallyunselected.Theyenableyoutoprovideuserswithalistofoptionsfromwhichonlyoneoptioncanbeselected. To create a radio button, set the type attribute of an <input> tag to radio. Tocreate a radio button group, set the name attributes of all the fields in the group to thesame value. To cre ate a radio button group with three options, the following code is used:Input
<p>Selectacolor:<br/>
<inputtype="radio"name="color"value="red"/>Red<br/>
<inputtype="radio"name="color"value="blue"/>Blue<br/>
<inputtype="radio"name="color"value="green"/>Green<br/>
</p>
CreatingMenuswithselectandoption
The select element creates a menu that can be configured to enable users to select one ormore options from a pull-down menu or a scrollable menu that shows several options atonce. The <select> tag defines how the menu will be displayed and the name of theparameter associated with the field. The <option> tag is used to add selections to themenu. The default appearance of select lists is to display a pull-down list that enables theusertoselectoneofthe options.Here'sanexampleofhowoneiscreated:
Input
<p>Pleasepickatraveldestination:
<selectname="location">
<option>Indiana</option>
<option>Fuji</option>
<option>Timbuktu</option>
<option>Alaska</option>
</select>
</p>
Framesfordesigningagoodwebsite:
ThefirstHTMLdocumentyouneedtocreateiscalledtheframesetdocument.Inthisdocument, youdefinethelayoutofyourframes, andthelocationsofthe documentsto be
initiallyloadedineachframe.EachofthethreeHTMLdocumentsotherthantheframeset document, the ones that load in the frames, contain normal HTML tags thatdefine the contents of each separate frame area. These documents are referenced by theframesetdocument.
The<frameset>Tag
To create a frameset document, you begin with the <frameset> tag. When used in anHTML document, the <frameset> tag replaces the <body> tag, as shown in the followingcode:
<html>
<head>
<title>PageTitle</title>
</head>
<frameset>
..yourframesetgoeshere...
</frameset>
</html>
It's importantthatyouunderstandupfront how aframeset document differs from anormal HTML document. If you include a <frameset> tag in an HTML document, youcannotincludea<body> tagalso.
ThecolsAttribute
When you define a <frameset> tag, you must include one of two attributes as part of thetag definition. The first of these attributes is the cols attribute, which takes the followingform:
<framesetcols="columnwidth,columnwidth,...">
Input
<html>
<head>
<title>ThreeColumns</title>
</head>
<framesetcols="100,50%,*">
<framesrc="leftcol.html">
<framesrc="midcol.html">
<framesrc="rightcol.html">
</frameset>
</html>
TherowsAttribute
The rows attribute works the same as the cols attribute, except that it splits the screen intohorizontal frames rather than vertical ones. To split the screen into two frames of equalheight,youwouldwritethefollowing:
Input
<html>
<head>
<title>TwoRows</title>
</head>
<framesetrows="50%,50%">
<framesrc="toprow.html">
<framesrc="botrow.html">
</frameset>
</html>
The<frame>Tag
Afteryouhaveyourbasicframesetlaidout,youneedtoassociateanHTMLdocumentwitheachframebyusingthe<frame> tag,whichtakesthe followingform:
<framesrc="documentURL">
Foreachframedefinedinthe<frameset>tag,youmustincludeacorresponding<frame>tag,asshowninthefollowing:
Input
<html>
<head>
<title>TheFRAMETag</title>
</head>
<framesetrows="*,*,*">
<framesrc="document1.html"/>
<framesrc="document2.html"/>
<framesrc="document3.html"/>
</frameset>
</html>
ChangingFrameBorders
Start with the <frame> tag. By using two attributes, bordercolor and frameborder, you canturnbordersonandoffandspecifytheircolor.Youcanassignbordercoloranyvalidcolor value, either as a name or a hexadecimal triplet. frameborder takes two possiblevalues:
1(todisplayborders)or0(toturnoffthedisplay ofborders).
<html>
<head>
<title>ConflictingBorders</title>
</head>
<framesetframeborder="0"rows="*,*,*">
<frameframeborder="1"bordercolor="yellow"src="document1.html">
<framebordercolor="#cc3333"src="document2.html">
<framesrc="document3.html">
</frameset>
</html>
longquestions:
1. Whatisinternet?WantisWWW?Whatisthedifferencebetweenthem?
2. Whatarethedifferentlistsavailableexplainbriefly.
3. Explainthedifferenttagsand attributesavailableintablebriefly.
4. Whatarethedifferent tagsavailabletocreatetheelementsofaformexplainindetail.
Unit 4 - PERL INTRODUCTION , Java Script, Java Applet
PERL: Introduction, Variable, Condition, Loop, Array, Implementing data structure, Hash, String, Regular Expression, File handling, I/O handling. JavaScript: Basics, Statements, comments, variable, comparison, condition, switch, loop, break. Object - string, array, Boolean, reg-ex. Function, Errors, Validation. Cookies: Definition of cookies, Create and Store a cookie with example. Java Applets: Container Class, Components, Applet Life Cycle, Update method; Parameter passing applet, Applications.
PERL - introduction
PERL is a high - level general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the PERL, but, the most commonly used expansion is “Practical Extraction and Reporting Language“. PERL supports both the procedural and Object-Oriented programming. PERL is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. It was originally designed for text processing, but has since evolved to become a full-featured programming language that is widely used in web development, system administration, network programming, and more.
Perl has a wide range of applications, including:
- Web development: Perl is commonly used for server-side web development, with popular frameworks such as Catalyst and Dancer.
- Text processing: Perl’s powerful regular expression support makes it ideal for text processing tasks, such as parsing log files, extracting data from web pages, and manipulating text files.
- System administration: Perl is often used for system administration tasks, such as automating system backups, managing configuration files, and monitoring system resources.
- Network programming: Perl can be used for network programming, with modules available for tasks such as sending email, communicating with web services, and building network protocols.
- Bioinformatics: Perl is widely used in bioinformatics, with popular modules such as BioPerl providing a powerful toolkit for biological data analysis and manipulation.
- GUI development: Perl can be used for GUI development with toolkits such as Perl/Tk, allowing developers to create cross-platform desktop applications.
Advantages of Perl:
- Perl Provides supports for cross platform and it is compatible with mark-up languages like HTML, XML etc.
- It is very efficient in text-manipulation i.e. Regular Expression. It also provides the socket capability.
- It is free and Open Source software.
- It is an embeddable language that’s why it can embed in web servers and database servers.
- It supports more than 25, 000 open source modules on CPAN(Comprehensive Perl Archive Network) which provide many powerful extensions to the standard library. For example, XML processing, GUI(Graphical User Interface) and DI(Database Integration) etc.
- Flexibility: Perl is a flexible language that allows programmers to solve problems using a variety of approaches, making it easy to write code quickly and efficiently.
- Regular expressions: Perl has excellent support for regular expressions, which makes it ideal for text
- processing and data manipulation tasks.
- Large library of modules: Perl has a vast library of modules that can be used to extend its functionality, making it easy to add complex
- features to your programs without having to reinvent the wheel.
- Cross-platform support: Perl runs on a wide range of platforms, including Windows, Linux, macOS, and more.
- Easy to learn: Perl has a relatively simple syntax and is easy to learn, especially for programmers who are familiar with other scripting languages.
Disadvantages of Perl:
- Perl doesn’t supports portability due to CPAN modules.
- Programs runs slowly and program needs to be interpreted each time when any changes are made.
- In Perl, the same result can be achieved in several different ways which make the code untidy as well as unreadable.
- Usability factor is lower when compared to other languages.
- Complex syntax: Perl’s flexibility can also be a disadvantage, as it can lead to code that is difficult to read and maintain, especially for developers who are new to the language.
- Performance: Perl is an interpreted language, which means that it can be slower than compiled languages like C or Java for large or computationally intensive programs.
- Legacy code: Because Perl has been around for over 30 years, there is a lot of legacy code written in earlier versions of the language that may not be compatible with newer versions.
- Security: Perl has some security concerns, such as the possibility of code injection attacks if the input data is not properly sanitized.
Variables:
Variables are used to store and manipulate data throughout the program.
Once a variable is created , variable occupies the memory space.
Variables can store integer, decimals or strings.
Variables in PERL is case sensitive.
Declaration of a variable
Variable declaration is declaring a variable belongs to a particular datatype, for example integer, decimal or string
Scalar Variable
Used to declare as single string or integer. It starts with “$” symbol.
Syntax: $var_name=value; |
Example:
$emp_name = “RAJA”;
$emp_no = CS100;
Array Variables:
Used to store randomly ordered set of values in a single variable name called array. It starts with @ symbol.
Syntax: @var_name=(val1,val2,val3,…); |
Example:
@rate_list = (70, 30, 40);
@item_list = ("Pen", "Pencil", "Sharpner");
Hash Variables:
Used to stored (key, value) pair efficiently accessed per key. It starts with % symbol.
Syntax : %var_name = ( key1=>val1, key2=>val2, key3=>val3, …..); |
Example:
%item_pairs = ("Pen" =>2, "Penci”=>3);
%empname_empno = ("Raja" =>100, "Rani"=>200);
JAVASCRIPT
JavaScript is the scripting language of the Web.
JavaScript is used in millions of Web pages to add functionality, validate forms, detect browsers, and much more.
Introduction to JavaScript
JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create cookies, and much more.
JavaScript is the most popular scripting language on the Internet, and works in all major browsers, such as Internet Explorer, Mozilla Firefox, and Opera.
What is JavaScript?
· JavaScript was designed to add interactivity to HTML pages
· JavaScript is a scripting language
· A scripting language is a lightweight programming language
· JavaScript is usually embedded directly into HTML pages
· JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
· Everyone can use JavaScript without purchasing a license
Java and JavaScript are two completely different languages in both concept and design!
Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in the same category as C and C++.
What can a JavaScript Do ?
· JavaScript gives HTML designers a programming tool - HTML authors are normally not programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can put small "snippets" of code into their HTML pages
· JavaScript can put dynamic text into an HTML page - A JavaScript statement like this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
· JavaScript can react to events - A JavaScript can be set to execute when something happens, like when a page has finished loading or when a user clicks on an HTML element
· JavaScript can read and write HTML elements - A JavaScript can read and change the content of an HTML element
· JavaScript can be used to validate data - A JavaScript can be used to validate form data before it is submitted to a server. This saves the server from extra processing
· JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load another page specifically designed for that browser
· JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
· information on the visitor's computer.
JavaScript Variables
Variables are "containers" for storing information. JavaScript variables are used to hold values or expressions.
A variable can have a short name, like x, or a more descriptive name, like carname. Rules for JavaScript variable names:
· Variable names are case sensitive (y and Y are two different variables)
· Variable names must begin with a letter or the underscore character Note: Because JavaScript is case-sensitive, variable names are case-sensitive. Example
A variable's value can change during the execution of a script. You can refer to a variable by its name to display or change its value.
<html>
<body>
<script type="text/javascript"> var firstname; firstname="Welcome"; document.write(firstname); document.write("<br />"); firstname="XYZ"; document.write(firstname);
</script>
<p>The script above declares a variable,
assigns a value to it, displays the value, change the value, and displays the value again.</p>
</body>
</html>
Output :
Welcome XYZ
The script above declares a variable, assigns a value to it, displays the value, change the value, and displays the value again.
Declaring (Creating) JavaScript Variables
Creating variables in JavaScript is most often referred to as "declaring" variables. You can declare JavaScript variables with the var statement:
var x; var carname; |
After the declaration shown above, the variables are empty (they have no values yet). However, you can also assign values to the variables when you declare them:
var x=5; var carname="Scorpio"; |
After the execution of the statements above, the variable x will hold the value 5, and carname will hold the value Scorpio.
Note: When you assign a text value to a variable, use quotes around the value.
Assigning Values to Undeclared JavaScript Variables
If you assign values to variables that have not yet been declared, the variables will automatically be declared.
These statements:
x=5; carname="Scorpio"; |
have the same effect as:
var x=5; var carname="Scorpio"; |
Redeclaring JavaScript Variables
If you redeclare a JavaScript variable, it will not lose its original value.
var x=5; var x; |
After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it.
DataTypes
· Numbers - are values that can be processed and calculated. You don't enclose them in quotation marks. The numbers can be either positive or negative.
· Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string literally; it doesn't process it. You'll use strings for text you want displayed or values you want passed along.
· Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified criteria.
· Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is the absence of any value.
Data Types
TYPE |
EXAMPLE |
Numbers |
Any number, such as 17, 21, or 54e7 |
Strings |
"Greetings!" or "Fun" |
Boolean |
Either true or false |
Null |
A special keyword for exactly that – the null value (that is, nothing) |
JavaScript Arithmetic
As with algebra, you can do arithmetic operations with JavaScript variables:
y=x-5; z=y+5; |
JavaScript Operators
The operator = is used to assign values. The operator + is used to add values.
The assignment operator = is used to assign values to JavaScript variables. The arithmetic operator + is used to add values together.
y=5; z=2; x=y+z; |
The value of x, after the execution of the statements above is 7.
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or values. Given that y=5, the table below explains the arithmetic operators:
Operator |
Description |
Example |
Result |
+ |
Addition |
x=y+2 |
x=7 |
- |
Subtraction |
x=y-2 |
x=3 |
* |
Multiplication |
x=y*2 |
x=10 |
/ |
Division |
x=y/2 |
x=2.5 |
% |
Modulus (division remainder) |
x=y%2 |
x=1 |
++ |
Increment |
x=++y |
x=6 |
-- |
Decrement |
x=--y |
x=4 |
JavaScript Assignment Operators
Assignment operators are used to assign values to JavaScript variables. Given that x=10 and y=5, the table below explains the assignment operators:
Operator |
Example |
Same As |
Result |
= |
x=y |
|
x=5 |
+= |
x+=y |
x=x+y |
x=15 |
-= |
x-=y |
x=x-y |
x=5 |
*= |
x*=y |
x=x*y |
x=50 |
/= |
x/=y |
x=x/y |
x=2 |
%= |
x%=y |
x=x%y |
x=0 |
The + Operator Used on Strings
The + operator can also be used to add string variables or text values together. To add two or more string variables together, use the + operator.
txt1="What a very"; txt2="nice day"; txt3=txt1+txt2; |
After the execution of the statements above, the variable txt3 contains "What a verynice day". To add a space between the two strings, insert a space into one of the strings:
txt1="What a very "; txt2="nice day"; txt3=txt1+txt2; |
or insert a space into the expression:
txt1="What a very"; txt2="nice day"; txt3=txt1+" "+txt2; |
After the execution of the statements above, the variable txt3 contains: "What a very nice day"
Adding Strings and Numbers
Look at these examples:
x=5+5; document.write(x);
x="5"+"5"; document.write(x);
x=5+"5"; document.write(x);
x="5"+5; document.write(x); |
The rule is:
If you add a number and a string, the result will be a string. JavaScript Comparison and Logical Operators
Comparison and Logical operators are used to test for true or false.
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given that x=5, the table below explains the comparison operators:
Operator |
Description |
Example |
== |
is equal to |
x==8 is false |
=== |
is exactly equal to (value and type) |
x===5 is true x==="5" is false |
!= |
is not equal |
x!=8 is true |
> |
is greater than |
x>8 is false |
< |
is less than |
x<8 is true |
>= |
is greater than or equal to |
x>=8 is false |
<= |
is less than or equal to |
x<=8 is true |
How Can it be Used
Comparison operators can be used in conditional statements to compare values and take action depending on the result:
if (age<18) document.write("Too young"); |
You will learn more about the use of conditional statements in the next chapter of this tutorial.
Logical Operators
Logical operators are used to determine the logic between variables or values. Given that x=6 and y=3, the table below explains the logical operators:
Operator |
Description |
Example |
&& |
and |
(x < 10 && y > 1) is true |
|| |
or |
(x==5 || y==5) is false |
! |
not |
!(x==y) is true |
Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.
variablename=(condition)?value1:value2 |
Syntax
greeting=(visitor=="PRES")?"Dear President ":"Dear "; |
Example
If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value "Dear President " else it will be assigned "Dear".
Conditional Statements
Very often when you write code, you want to perform different actions for different decisions. You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
· if statement - use this statement if you want to execute some code only if a specified condition is true
· if...else statement - use this statement if you want to execute some code if the condition is true and another code if the condition is false
· if...else if.... else statement - use this statement if you want to select one of many blocks of code to
be executed
· switch statement - use this statement if you want to select one of many blocks of code to be executed
If Statement
You should use the if statement if you want to execute some code only if a specified condition is true.
if (condition) { code to be executed if condition is true } |
Syntax
Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!
<script type="text/javascript"> //Write a "Good morning" greeting if //the time is less than 10 var d=new Date(); var time=d.getHours(); |
Example 1
if (time<10) { document.write("<b>Good morning</b>"); } </script> |
<script type="text/javascript"> //Write "Lunch-time!" if the time is 11 var d=new Date(); var time=d.getHours();
if (time==11) { document.write("<b>Lunch-time!</b>"); } </script> |
Example 2
Note: When comparing variables you must always use two equals signs next to each other (==)!
Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the specified condition is true.
If...else Statement
If you want to execute some code if a condition is true and another code if the condition is not true, use the if else statement.
if (condition) { code to be executed if condition is true } else { code to be executed if condition is not true } |
Syntax
<script type="text/javascript"> //If the time is less than 10, //you will get a "Good morning" greeting. //Otherwise you will get a "Good day" greeting. var d = new Date(); |
Example
var time = d.getHours();
if (time < 10) { document.write("Good morning!"); } else { document.write("Good day!"); } </script> |
If...else if...else Statement
You should use the if....else if...else statement if you want to select one of many sets of lines to execute.
if (condition1) { code to be executed if condition1 is true } else if (condition2) { code to be executed if condition2 is true } else { code to be executed if condition1 and condition2 are not true } |
Syntax
<script type="text/javascript"> var d = new Date() var time = d.getHours() if (time<10) { document.write("<b>Good morning</b>"); } else if (time>10 && time<16) { document.write("<b>Good day</b>"); } else |
Example
{ document.write("<b>Hello World!</b>"); } </script> |
The JavaScript Switch Statement
You should use the switch statement if you want to select one of many blocks of code to be executed.
switch(n) { case 1: execute code block 1 break; case 2: execute code block 2 break; default: code to be executed if n is different from case 1 and 2 } |
Syntax
This is how it works: First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then compared with the values for each case in the structure. If there is a match, the block of code associated with that case is executed. Use break to prevent the code from running into the next case automatically.
<script type="text/javascript"> //You will receive a different greeting based //on what day it is. Note that Sunday=0, //Monday=1, Tuesday=2, etc. var d=new Date(); theDay=d.getDay(); switch (theDay) { case 5: document.write("Finally Friday"); break; case 6: document.write("Super Saturday"); break; case 0: document.write("Sleepy Sunday"); |
Example
break; default: document.write("I'm looking forward to this weekend!"); } </script> |
JavaScript Controlling(Looping) Statements
Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.
JavaScript Loops
Very often when you write code, you want the same block of code to run over and over again in a row. Instead of adding several almost equal lines in a script we can use loops to perform a task like this.
In JavaScript there are two different kind of loops:
· for - loops through a block of code a specified number of times
· while - loops through a block of code while a specified condition is true
The for Loop
The for loop is used when you know in advance how many times the script should run.
Syntax
for (var=startvalue;var<=endvalue;var=var+increment) { code to be executed } |
Example
Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing statement.
<html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { |
document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> |
Result
The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 |
JavaScript While Loop
Loops in JavaScript are used to execute the same block of code a specified number of times or while a specified condition is true.
The while loop
The while loop is used when you want the loop to execute and continue executing while the specified condition is true.
while (var<=endvalue) { code to be executed } |
Note: The <= could be any comparing statement.
Example
Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
<html> |
<body> <script type="text/javascript"> var i=0; while (i<=10) { document.write("The number is " + i); document.write("<br />"); i=i+1; } </script> </body> </html> |
Result
The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 |
The do...while Loop
The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE, and then it will repeat the loop as long as the specified condition is true. This loop will always be executed at least once, even if the condition is false, because the code is executed before the condition is tested.
do { code to be executed } while (var<=endvalue); |
Example
<html> <body> <script type="text/javascript"> |
var i=0; do { document.write("The number is " + i); document.write("<br />"); i=i+1; } while (i<0); </script> </body> </html> |
Result
The number is 0 |
JavaScript Break and Continue
There are two special statements that can be used inside loops: break and continue.
JavaScript break and continue Statements
There are two special statements that can be used inside loops: break and continue.
Break
The break command will break the loop and continue executing the code that follows after the loop (if any).
Example
<html> <body> <script type="text/javascript"> var i=0; for (i=0;i<=10;i++) { if (i==3) { break; } document.write("The number is " + i); document.write("<br />"); } </script> </body> |
</html> |
Result
The number is 0 The number is 1 The number is 2 |
Continue
The continue command will break the current loop and continue with the next value.
Example
<html> <body> <script type="text/javascript"> var i=0 for (i=0;i<=10;i++) { if (i==3) { continue; } document.write("The number is " + i); document.write("<br />"); } </script> </body> </html> |
Result
The number is 0 The number is 1 The number is 2 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 The number is 10 |
JavaScript Functions
A function (also known as a method) is a self-contained piece of code that performs a particular "function". You can recognise a function by its format - it's a piece of descriptive text, followed by open and close brackets.A function is a reusable code-block that will be executed by an event, or when the function is called.
To keep the browser from executing a script when the page loads, you can put your script into a function. A function contains code that will be executed by an event or by a call to that function.
You may call a function from anywhere within the page (or even from other pages if the function is embedded in an external .js file).
Functions can be defined both in the <head> and in the <body> section of a document. However, to assure that the function is read/loaded by the browser before it is called, it could be wise to put it in the
<head> section.
<html> <head> <script type="text/javascript"> function displaymessage() { alert("Hello World!"); } </script> </head> <body> <form> <input type="button" value="Click me!" onclick="displaymessage()" > </form> </body> </html> |
Example
If the line: alert("Hello world!!") in the example above had not been put within a function, it would have been executed as soon as the line was loaded. Now, the script is not executed before the user hits the button. We have added an onClick event to the button that will execute the function displaymessage() when the button is clicked.
You will learn more about JavaScript events in the JS Events chapter.
How to Define a Function
The syntax for creating a function is:
function functionname(var1,var2,...,varX) { some code } |
var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of the function.
Note: A function with no parameters must include the parentheses () after the function name:
function functionname() { some code } |
Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the exact same capitals as in the function name.
The return Statement
The return statement is used to specify the value that is returned from the function. So, functions that are going to return a value must use the return statement.
Example
The function below should return the product of two numbers (a and b):
function prod(a,b) { x=a*b; return x; } |
When you call the function above, you must pass along two parameters:
product=prod(2,3); |
The returned value from the prod() function is 6, and it will be stored in the variable called product.
The Lifetime of JavaScript Variables
When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
What is an Event?
Event Handlers
Event Handlers are JavaScript methods, i.e. functions of objects, that allow us as JavaScript programmers to control what happens when events occur.
Directly or indirectly, an Event is always the result of something a user does. For example, we've already seen Event Handlers like onClick and onMouseOver that respond to mouse actions. Another type of Event, an internal change-of-state to the page (completion of loading or leaving the page). An onLoad Event can be considered an indirect result of a user action.
Although we often refer to Events and Event Handlers interchangeably, it's important to keep in mind the distinction between them. An Event is merely something that happens - something that it is initiated by an Event Handler (onClick, onMouseOver, etc...).
The elements on a page which can trigger events are known as "targets" or "target elements," and we can easily understand how a button which triggers a Click event is a target element for this event. Typically, events are defined through the use of Event Handlers, which are bits of script that tell the browser what to do when a particular event occurs at a particular target. These Event Handlers are commonly written as attributes of the target element's HTML tag.
The Event Handler for a Click event at a form field button element is quite simple to understand:
<INPUT TYPE="button" NAME="click1" VALUE="Click me for fun!"
onClick="event_handler_code">
The event_handler_code portion of this example is any valid JavaScript and it will be executed when the specified event is triggered at this target element. This particular topic will be continued in Incorporating JavaScripts into your HTML pages.
There are "three different ways" that Event Handlers can be used to trigger Events or Functions.
Method 1 (Link Events):
Places an Event Handler as an attribute within an <A HREF= > tag, like this:
<A HREF="foo.html" onMouseOver="doSomething()"> ... </A>
You can use an Event Handler located within an <A HREF= > tag to make either an image or a text link respond to a mouseover Event. Just enclose the image or text string between the <A HREF= > and the
</A> tags.
Whenever a user clicks on a link, or moves her cursor over one, JavaScript is sent a Link Event. One Link Event is called onClick, and it gets sent whenever someone clicks on a link. Another link event is called onMouseOver. This one gets sent when someone moves the cursor over the link.
You can use these events to affect what the user sees on a page. Here's an example of how to use link events. Try it out, View Source, and we'll go over it.
<A HREF="javascript:void('')"
onClick="open('index.htm', 'links', 'height=200,width=200');">How to Use Link Events
</A>
The first interesting thing is that there are no <SCRIPT> tags. That's because anything that appears in the quotes of an onClick or an onMouseOver is automatically interpreted as JavaScript. In fact, because semicolons mark the end of statements allowing you to write entire JavaScripts in one line, you can fit an entire JavaScript program between the quotes of an onClick. It'd be ugly, but you could do it.
Here are the three lines of interest:
1. <A HREF="#" onClick="alert('Ooo, do it again!');">Click on me!</A>
2. <A HREF="javascript:void('')" onClick="alert('Ooo, do it again!');"> Click on me!
</A>
3. <A HREF="javascript:alert('Ooo, do it again!')" >Click on me!</A>
In the first example we have a normal <A> tag, but it has the magic onClick="" element, which says, "When someone clicks on this link, run the little bit of JavaScript between my quotes." Notice, there's even a terminating semicolon at the end of the alert. Question: is this required? NO.
Let's go over each line:
1. HREF="#" tells the browser to look for the anchor #, but there is no anchor "#", so the browser reloads the page and goes to top of the page since it couldn't find the anchor.
2. <A HREF="javascript:void('')" tells the browser not to go anywhere - it "deadens" the link when you click on it. HREF="javascript: is the way to call a function when a link (hyperlink or an HREFed image) is clicked.
3. HREF="javascript:alert('Ooo, do it again!')" here we kill two birds with one stone. The default behavior of a hyperlink is to click on it. By clicking on the link we call the window Method alert() and also at the same time "deaden" the link.
The next line is
<A HREF="javascript:void('')" onMouseOver="alert('Hee hee!');"> Mouse over me!
</A>
This is just like the first line, but it uses an onMouseOver instead of an onClick. Method 2 (Actions within FORMs):
The second technique we've seen for triggering a Function in response to a mouse action is to place an
onClick Event Handler inside a button type form element, like this:
<FORM>
<INPUT TYPE="button" onClick="doSomething()">
</FORM>
While any JavaScript statement, methods, or functions can appear inside the quotation marks of an Event Handler, typically, the JavaScript script that makes up the Event Handler is actually a call to a function defined in the header of the document or a single JavaScript command. Essentially, though, anything that appears inside a command block (inside curly braces {}) can appear between the quotation marks.
For instance, if you have a form with a text field and want to call the function checkField() whenever the value of the text field changes, you can define your text field as follows:
<INPUT TYPE="text" onChange="checkField(this)">
Nonetheless, the entire code for the function could appear in quotation marks rather than a function call:
<INPUT TYPE="text" onChange="if (this.value <= 5) {
alert("Please enter a number greater than 5");
}">
To separate multiple commands in an Event Handler, use semicolons
<INPUT TYPE="text" onChange="alert(‘Thanks for the entry.’);
confirm(‘Do you want to continue?’);">
The advantage of using functions as Event Handlers, however, is that you can use the same Event Handler code for multiple items in your document and, functions make your code easier to read and understand.
Method 3 (BODY onLoad & onUnLoad):
The third technique is to us an Event Handler to ensure that all required objects are defined involve the onLoad and onUnLoad. These Event Handlers are defined in the <BODY> or <FRAMESET> tag of an HTML file and are invoked when the document or frameset are fully loaded or unloaded. If you set a flag
within the onLoad Event Handler, other Event Handlers can test this flags to see if they can safely run, with the knowledge that the document is fully loaded and all objects are defined. For example:
<SCRIPT>
var loaded = false; function doit() {
// alert("Everything is \"loaded\" and loaded = " + loaded);
alert('Everything is "loaded" and loaded = ' + loaded);
}
</SCRIPT>
<BODY onLoad="loaded = true;">
-- OR --
<BODY onLoad="window.loaded = true;">
<FORM>
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (window.loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded) doit();">
</FORM>
</BODY>
The onLoad Event Handler is executed when the document or frameset is fully loaded, which means that all images have been downloaded and displayed, all subframes have loaded, any Java Applets and Plugins (Navigator) have started running, and so on. The onUnLoad Event Handler is executed just before the page is unloaded, which occurs when the browser is about to move on to a new page. Be aware that when you are working with multiple frames, there is no guarantee of the order in which the onLoad Event Handler is invoked for the various frames, except that the Event Handlers for the parent frame is invoked after the Event Handlers of all its children frames -- This will be discussed in detail in Week 8.
Setting the bgColor Property
The first example allows the user to change the color by clicking buttons, while the second example allows you to change colors by using drop down boxes.
Event Handlers
EVENT |
DESCRIPTION |
onAbort |
the user cancels loading of an image |
onBlur |
input focus is removed from a form element (when the user clicks outside the field) or focus is removed from a window |
onClick |
the user clicks on a link or form element |
onChange |
the value of a form field is changed by the user |
onError |
an error happens during loading of a document or image |
onFocus |
input focus is given to a form element or a window |
onLoad |
once a page is loaded, NOT while loading |
onMouseOut |
the user moves the pointer off of a link or clickable area of an image map |
onMouseOver |
the user moves the pointer over a hypertext link |
onReset |
the user clears a form using the Reset button |
onSelect |
the user selects a form element’s field |
onSubmit |
a form is submitted (ie, when the users clicks on a submit button) |
onUnload |
the user leaves a page |
Note: Input focus refers to the act of clicking on or in a form element or field. This can be done by clicking in a text field or by tabbing between text fields.
Which Event Handlers Can Be Used
OBJECT |
EVENT HANDLERS AVAILABLE |
Button element |
onClick, onMouseOver |
Checkbox |
onClick |
Clickable ImageMap area |
onClick, onMouseOver, onMouseOut |
Document |
onLoad, onUnload, onError |
Form |
onSubmit, onReset |
Framesets |
onBlur, onFocus |
Hypertext link |
onClick, onMouseOver, onMouseOut |
Image |
onLoad, onError, onAbort |
Radio button |
onClick |
Reset button |
onClick |
Selection list |
onBlur, onChange, onFocus |
Submit button |
onClick |
TextArea element |
onBlur, onChange, onFocus, onSelect |
Text element |
onBlur, onChange, onFocus, onSelect |
Window |
onLoad, onUnload, onBlur, onFocus |
JavaScript Arrays
An array object is used to create a database-like structure within a script. Grouping data points (array elements) together makes it easier to access and use the data in a script. There are methods of accessing actual databases (which are beyond the scope of this series) but here we're talking about small amounts of data.
An array can be viewed like a column of data in a spreadsheet. The name of the array would be the same as the name of the column. Each piece of data (element) in the array is referred to by a number (index), just like a row number in a column.
An array is an object. Earlier, I said that an object is a thing, a collection of properties (array elements, in this case) grouped together.
You can name an array using the same format as a variable, a function or an object. Remember our basic rules: The first character cannot be a number, you cannot use a reserved word, and you cannot use spaces. Also, be sure to remember that the name of the array object is capitalized, e.g. Array.
The JavaScript interpreter uses numbers to access the collection of elements (i.e. the data) in an array. Each index number (as it is the number of the data in the array's index) refers to a specific piece of data in the array, similar to an ID number. It's important to remember that the index numbering of the data starts at "0." So, if you have 8 elements, the first element will be numbered "0" and the last one will be "7."
Elements can be of any type: character string, integer, Boolean, or even another array. An array can even have different types of elements within the same array. Each element in the
array is accessed by placing its index number in brackets, i.e. myCar[4]. This would mean that we are looking for data located in the array myCar which has an index of "4." Since the numbering of an index starts at "0," this would actually be the fifth index. For instance, in the following array,
var myCar = new Array("Chev","Ford","Buick","Lincoln","Truck"); alert(myCar[4])
the data point with an index of "4" would be Truck. In this example, the indexes are numbered as follows: 0=Chev, 1=Ford, 2=Buick, 3=Lincoln, and 4=Truck. When creating loops, it's much easier to refer to a number than to the actual data itself.
The Size of the Array
The size of an array is determined by either the actual number of elements it contains or by actually specifying a given size. You don't need to specify the size of the array. Sometimes, though, you may want to pre-set the size, e.g.:
var myCar = new Array(20);
That would pre-size the array with 20 elements. You might pre-size the array in order to set aside the space in memory.
Multidimensional Arrays
This type of an array is similar to parallel arrays. In a multidimensional array, instead of creating two or more arrays in tandem as we did with the parallel array, we create an array with several levels or "dimensions." Remember our example of a spreadsheet with rows and columns? This time, however, we have a couple more columns.
Multidimensional arrays can be created in different ways. Let's look at one of these method. First, we create the main array, which is similar to what we did with previous arrays.
var emailList = new Array();
Next, we create arrays for elements of the main array:
emailList[0] = new Array("President", "Paul Smith", "psmith@domain.com"); emailList[1] = new Array("Vice President", "Laura Stevens", "lstevens@domain.com"); emailList[2] = new Array("General Manager", "Mary Larsen", "mlarsen@domain.com"); emailList[3] = new Array("Sales Manager", "Bob Lark", "blark@domain.com");
In this script we created "sub arrays" or arrays from another level or "dimension." We used the name of the main array and gave it an index number (e.g., emailList[0]). Then we created a new instance of an array and gave it a value with three elements.
In order to access a single element, we need to use a double reference. For example, to get the e-mail address for the Vice President in our example above, access the third element "[2]" of the second element "[1]" of the array named emailList.
It would be written like this:
var vpEmail = emailList[1][2] alert("The address is: "+ vpEmail)
1. We declared a variable, named it emailList, and initialized it with a value of a new instance of an array.
2. Next, we created an array for each of the elements within the original array. Each of the new arrays contained three elements.
3. Then we declared a variable named vpEmail and initialized it with the value of the third element (lstevens@domain.com) of the second element "[1]" of the array named emailList.
You could also retrieve the information using something like: var title = emailList[1][0]
var email = emailList[1][2]
alert("The e-mail address for the " + title +" is: " + email)
Array Properties
length
The length property returns the number of elements in an array. The format is arrayName.length. The length property is particularly useful when using a loop to cycle through an array. One example would be an array used to cycle banners:
var bannerImg = new Array(); bannerImg[0]="image-1.gif"; bannerImg[1]="image-2.gif"; bannerImg[2]="image-3.gif";
var newBanner = 0
var totalBan = bannerImg.length
function cycleBan() { newBanner++
if (newBanner == totalBan) { newBanner = 0
}
document.banner.src=bannerImg[newBanner] setTimeout("cycleBan()", 3*1000)
}
window.onload=cycleBan;
This portion is then placed in the body where the banner is to be displayed: <img src="image-1.gif" name="banner">
Let's take a look and see what happened here:
1. On the first line, we created a new instance of the array bannerImg, and gave it three data elements. (Remember, we are only making a copy of the Array object here.)
2. Next, we created two variables: newBanner, which has a beginning value of zero; and totalBan, which returns the length of the array (the total number of elements contained in the array).
3. Then we created a function named cycleBan. This function will be used to create a loop to cycle the images.
a. We set the newBanner variable to be increased each time the function cycles. (Review: By placing the increment operator [" ++ "] after the variable [the "operand"], the variable is incremented only after it returns its current value to the script. For example, its beginning value is "0", so in the first cycle it will return a value of "0" to the script and then its value will be increased by "1".)
b. When the value of the newBanner variable is equal to the variable totalBan (which is the length of the array), it is then reset to "0". This allows the images to start the cycle again, from the beginning.
c. The next statement uses the Document Object Method (DOM - we'll be taking a look at that soon) to display the images on the Web page. Remember, we use the dot operator to access the properties of an object. We also read the statement backwards, i.e., "take the element from the array bannerImg, that is specified by the current value of the variable newBanner, and place it in the src attribute located in the element with the name attribute of banner, which is located in the document object."
d. We then used the setTimeout function to tell the script how long to display each image. This is always measured in milliseconds so, in this case, the function cycleBan is called every 3,000 milliseconds (i.e., every 3 seconds).
4. Finally, we used the window.onload statement to execute the function cycleBan as soon as the document is loaded.
There are a total of five properties for the Array object. In addition to the length property listed above, the others are:
1. constructor: Specifies the function that creates an object's prototype.
2. index: Only applies to JavaScript arrays created by a regular expression match.
3. input: Only applies to JavaScript arrays created by a regular expression match.
4. prototype: Used to add properties or methods.
The other properties listed here are either more advanced or seldom used. For now, we'll stick to the basics.
Javascript Object Hierarchy
Hierarchy Objects |
|||
Object |
Properties |
Methods |
Event Handlers |
Window |
defaultStatus frames opener parent scroll self status top window |
alert blur close confirm focus open prompt clearTimeout setTimeout |
onLoad onUnload onBlur onFocus |
History |
length forward go |
back |
none |
Navigator |
appCodeName appName appVersion mimeTypes plugins userAgent |
javaEnabled |
none |
document |
alinkColor anchors applets area bgColor cookie fgColor forms images lastModified linkColor links location referrer title |
clear close open write writeln |
none (the onLoad and onUnload event handlers belong to the Window object. |
|
vlinkColor |
|
|
|||
image |
border complete height hspace lowsrc name src vspace width |
none |
none |
|||
form |
action elements encoding FileUpload method name target |
submit reset |
onSubmit onReset |
|||
text |
defaultValue name type value |
focus blur select |
onBlur onCharge onFocus onSelect |
|||
Built-in Objects |
||||||
Array |
length |
join reverse sort xx |
none |
|||
Date |
none |
getDate getDay getHours getMinutes getMonth getSeconds getTime getTimeZoneoffset getYear parse prototype setDate setHours setMinutes setMonth setSeconds setTime |
none |
|||
|
|
setYear toGMTString toLocaleString UTC |
|
String |
length prototype |
anchor big blink bold charAt fixed fontColor fontSize indexOf italics lastIndexOf link small split strike sub substring sup toLowerCase toUpperCase |
Window |
JavaScript Array Object
The Array object is used to store multiple values in a single variable.
Create an Array
The following code creates an Array object called myCars:
var myCars=new Array(); |
There are two ways of adding values to an array (you can add as many values as you need to define as many variables you require).
1:
var myCars=new Array(); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; |
You could also pass an integer argument to control the array's size:
var myCars=new Array(3); myCars[0]="Saab"; myCars[1]="Volvo"; myCars[2]="BMW"; |
2:
var myCars=new Array("Saab","Volvo","BMW"); |
Note: If you specify numbers or true/false values inside the array then the type of variables will be numeric or Boolean instead of string.
Access an Array
You can refer to a particular element in an array by referring to the name of the array and the index number. The index number starts at 0.
The following code line:
document.write(myCars[0]); |
will result in the following output:
Saab |
Modify Values in an Array
To modify a value in an existing array, just add a new value to the array with a specified index number:
myCars[0]="Opel"; |
Now, the following code line:
document.write(myCars[0]); |
will result in the following output:
Opel |
JavaScript Date Object
Create a Date Object
The Date object is used to work with dates and times. The following code create a Date object called myDate:
var myDate=new Date() |
Note: The Date object will automatically hold the current date and time as its initial value!
Set Dates
We can easily manipulate the date by using the methods available for the Date object. In the example below we set a Date object to a specific date (14th January 2010):
var myDate=new Date(); myDate.setFullYear(2010,0,14); |
And in the following example we set a Date object to be 5 days into the future:
var myDate=new Date(); myDate.setDate(myDate.getDate()+5); |
Note: If adding five days to a date shifts the month or year, the changes are handled automatically by the Date object itself!
Compare Two Dates
The Date object is also used to compare two dates.
The following example compares today's date with the 14th January 2010:
var myDate=new Date(); myDate.setFullYear(2010,0,14); var today = new Date(); if (myDate>today) { alert("Today is before 14th January 2010"); } else { alert("Today is after 14th January 2010"); } |
JavaScript Math Object
Math Object
The Math object allows you to perform mathematical tasks.
The Math object includes several mathematical constants and methods.
Syntax for using properties/methods of Math:
var pi_value=Math.PI; var sqrt_value=Math.sqrt(16); |
Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an object without creating it.
Mathematical Constants
JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E, PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log of E.
You may reference these constants from your JavaScript like this:
Math.E Math.PI Math.SQRT2 Math.SQRT1_2 Math.LN2 Math.LN10 Math.LOG2E Math.LOG10E |
Mathematical Methods
In addition to the mathematical constants that can be accessed from the Math object there are also several methods available.
The following example uses the round() method of the Math object to round a number to the nearest integer:
document.write(Math.round(4.7)); |
The code above will result in the following output:
5 |
The following example uses the random() method of the Math object to return a random number between 0 and 1:
document.write(Math.random()); |
The code above can result in the following output:
0.4218824567728053 |
The following example uses the floor() and random() methods of the Math object to return a random number between 0 and 10:
document.write(Math.floor(Math.random()*11)); |
The code above can result in the following output:
4 |
JavaScript String Object
String object
The String object is used to manipulate a stored piece of text.
Examples of use:
The following example uses the length property of the String object to find the length of a string:
var txt="Hello world!"; document.write(txt.length); |
The code above will result in the following output:
12 |
The following example uses the toUpperCase() method of the String object to convert a string to uppercase letters:
var txt="Hello world!"; document.write(txt.toUpperCase()); |
The code above will result in the following output:
HELLO WORLD! |
Window Object
The Window object is the top level object in the JavaScript hierarchy. The Window object represents a browser window.
A Window object is created automatically with every instance of a <body> or <frameset> tag.
IE: Internet Explorer, F: Firefox, O: Opera.
Window Object Collections
Collection |
Description IE F |
O |
||
frames[] |
Returns all named frames in the window |
4 |
1 |
9 |
Window Object Properties
Property |
Description |
IE |
F |
O |
closed |
Returns whether or not a window has been closed |
4 |
1 |
9 |
defaultStatus |
Sets or returns the default text in the statusbar of the window |
4 |
No |
9 |
document |
See Document object |
4 |
1 |
9 |
history |
See History object |
4 |
1 |
9 |
length |
Sets or returns the number of frames in the window |
4 |
1 |
9 |
location |
See Location object |
4 |
1 |
9 |
name |
Sets or returns the name of the window |
4 |
1 |
9 |
opener |
Returns a reference to the window that created the window |
4 |
1 |
9 |
outerHeight |
Sets or returns the outer height of a window |
No |
1 |
No |
outerWidth |
Sets or returns the outer width of a window |
No |
1 |
No |
pageXOffset |
Sets or returns the X position of the current page in relation to the upper left corner of a window's display area |
No |
No |
No |
pageYOffset |
Sets or returns the Y position of the current page in relation to the upper left corner of a window's display area |
No |
No |
No |
parent |
Returns the parent window |
4 |
1 |
9 |
personalbar |
Sets whether or not the browser's personal bar (or directories bar) should be visible |
|
|
|
scrollbars |
Sets whether or not the scrollbars should be visible |
|
|
|
self |
Returns a reference to the current window |
4 |
1 |
9 |
status |
Sets the text in the statusbar of a window |
4 |
No |
9 |
statusbar |
Sets whether or not the browser's statusbar should be visible |
|
|
|
toolbar |
Sets whether or not the browser's tool bar is visible or not (can only be set before the window is opened and you must have UniversalBrowserWrite privilege) |
|
|
|
top |
Returns the topmost ancestor window |
4 |
1 |
9 |
Window Object Methods
Method |
Description |
IE |
F |
O |
|
alert() |
Displays an alert box with a message and an OK button |
4 |
1 |
9 |
|
blur() |
Removes focus from the current window |
4 |
1 |
9 |
|
clearInterval() |
Cancels a timeout set with setInterval() |
4 |
1 |
9 |
|
clearTimeout() |
Cancels a timeout set with setTimeout() |
4 |
1 |
9 |
|
close() |
Closes the current window |
4 |
1 |
9 |
|
confirm() |
Displays a dialog box with a message and an OK and a Cancel button |
4 |
1 |
9 |
|
|
|
||||
createPopup() |
Creates a pop-up window |
4 |
No |
No |
|
focus() |
Sets focus to the current window |
4 |
1 |
9 |
|
moveBy() |
Moves a window relative to its current position |
4 |
1 |
9 |
|
moveTo() |
Moves a window to the specified position |
4 |
1 |
9 |
|
open() |
Opens a new browser window |
4 |
1 |
9 |
|
print() |
Prints the contents of the current window |
5 |
1 |
9 |
|
prompt() |
Displays a dialog box that prompts the user for input |
4 |
1 |
9 |
|
resizeBy() |
Resizes a window by the specified pixels |
4 |
1 |
9 |
|
resizeTo() |
Resizes a window to the specified width and height |
4 |
1.5 |
9 |
|
scrollBy() |
Scrolls the content by the specified number of pixels |
4 |
1 |
9 |
|
scrollTo() |
Scrolls the content to the specified coordinates |
4 |
1 |
9 |
|
setInterval() |
Evaluates an expression at specified intervals |
4 |
1 |
9 |
|
setTimeout() |
Evaluates an expression after a specified number of milliseconds |
4 |
1 |
9 |
|
Document Object
The Document object represents the entire HTML document and can be used to access all elements in a page.
The Document object is part of the Window object and is accessed through the window.document property.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).
Document Object Collections
Collection |
Description |
IE |
F |
O |
W3C |
|||
anchors[] |
Returns a reference to all Anchor objects in the document |
4 |
1 |
9 |
Yes |
|||
|
|
|||||||
forms[] |
Returns a reference to all Form objects in the document |
4 |
1 |
9 |
Yes |
|||
|
|
|||||||
images[] |
Returns a reference to all Image objects in the document |
4 |
1 |
9 |
Yes |
|||
|
|
|||||||
links[] |
Returns a reference to all Area and Link objects in |
4 |
1 9 |
Yes |
||||
|
the document |
|
|
|
Document Object Properties
Property |
Description |
IE |
F |
O |
W3C |
|||
body |
Gives direct access to the <body> element |
|
|
|
|
|||
cookie |
Sets or returns all cookies associated with the current document |
4 |
1 |
9 |
Yes |
|||
|
|
|||||||
domain |
Returns the domain name for the current document |
4 |
1 |
9 |
Yes |
|||
lastModified |
Returns the date and time a document was last modified |
4 |
1 |
No |
No |
|||
|
|
|||||||
referrer |
Returns the URL of the document that loaded the current document |
4 |
1 |
9 |
Yes |
|||
|
|
|||||||
title |
Returns the title of the current document |
4 |
1 |
9 |
Yes |
|||
URL |
Returns the URL of the current document |
4 |
1 9 |
Yes |
||||
Document Object Methods
Method |
Description |
IE |
F |
O |
W3C |
|||||
close() |
Closes an output stream opened with the document.open() method, and displays the collected data |
4 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
getElementById() |
Returns a reference to the first object with the specified id |
5 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
getElementsByName() |
Returns a collection of objects with the specified name |
5 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
getElementsByTagName() |
Returns a collection of objects with the specified tagname |
5 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
open() |
Opens a stream to collect the output from any document.write() or document.writeln() methods |
4 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
write() |
Writes HTML expressions or JavaScript code to a document |
4 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
writeln() |
Identical to the write() method, with the addition of writing a new line character after each expression |
4 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
History Object
The History object is actually a JavaScript object, not an HTML DOM object.
The History object is automatically created by the JavaScript runtime engine and consists of an array of URLs. These URLs are the URLs the user has visited within a browser window.
The History object is part of the Window object and is accessed through the window.history property.
IE: Internet Explorer, F: Firefox, O: Opera.
History Object Properties
Property |
Description |
IE |
F |
O |
length |
Returns the number of elements in the history list |
4 |
1 9 |
History Object Methods
Method |
Description |
IE |
F |
O |
back() |
Loads the previous URL in the history list |
4 |
1 |
9 |
forward() |
Loads the next URL in the history list |
4 |
1 |
9 |
go() |
Loads a specific page in the history list |
4 |
1 9 |
Form Object
The Form object represents an HTML form.
For each instance of a <form> tag in an HTML document, a Form object is created.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).
Form Object Collections
Collection |
Description IE |
F |
O |
W3C |
|
elements[] |
Returns an array containing each element in the form |
5 |
1 |
9 |
Yes |
Form Object Properties
Property |
Description |
IE |
F |
O |
W3C |
|
acceptCharset |
Sets or returns a list of possible character-sets for the form data |
No |
No |
No |
Yes |
|
action |
Sets or returns the action attribute of a form |
5 |
1 |
9 |
Yes |
|
enctype |
Sets or returns the MIME type used to encode the content of a form |
6 |
1 |
9 |
Yes |
|
|
|
|||||
id |
Sets or returns the id of a form |
5 |
1 |
9 |
Yes |
|
length |
Returns the number of elements in a form |
5 |
1 |
9 |
Yes |
|
method |
Sets or returns the HTTP method for sending data to the server |
5 |
1 |
9 |
Yes |
|
name |
Sets or returns the name of a form |
5 |
1 |
9 |
Yes |
|
target |
Sets or returns where to open the action-URL in a form |
5 |
1 9 |
Yes |
||
Standard Properties
Property |
Description |
IE |
F |
O |
W3C |
className |
Sets or returns the class attribute of an element |
5 |
1 |
9 |
Yes |
dir |
Sets or returns the direction of text |
5 |
1 |
9 |
Yes |
lang |
Sets or returns the language code for an element |
5 |
1 |
9 |
Yes |
title |
Sets or returns an element's advisory title |
5 |
1 |
9 |
Yes |
Form Object Methods
Method |
Description |
IE |
F |
O |
W3C |
reset() |
Resets the values of all elements in a form |
5 |
1 |
9 |
Yes |
submit() |
Submits a form |
5 |
1 9 |
Yes |
Image Object
The Image object represents an embedded image.
For each instance of an <img> tag in an HTML document, an Image object is created.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).
Image Object Properties
Property |
Description |
IE |
F |
O |
W3C |
|||||
align |
Sets or returns how to align an image according to the surrounding text |
5 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
alt |
Sets or returns an alternate text to be displayed, if a browser cannot show an image |
5 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
border |
Sets or returns the border around an image |
4 |
1 |
9 |
Yes |
|||||
complete |
Returns whether or not the browser has finished loading the image |
4 |
1 |
9 |
No |
|||||
|
|
|||||||||
height |
Sets or returns the height of an image |
4 |
1 |
9 |
Yes |
|||||
hspace |
Sets or returns the white space on the left and right side of the image |
4 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
id |
Sets or returns the id of the image |
4 |
1 |
9 |
Yes |
|||||
isMap |
Returns whether or not an image is a server-side image map |
5 |
1 |
9 |
Yes |
|||||
longDesc |
Sets or returns a URL to a document containing a description of the image |
6 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
lowsrc |
Sets or returns a URL to a low-resolution version of an image |
4 |
1 |
9 |
No |
|||||
name |
Sets or returns the name of an image |
4 |
1 |
9 |
Yes |
|||||
src |
Sets or returns the URL of an image |
4 |
1 |
9 |
Yes |
|||||
useMap |
Sets or returns the value of the usemap attribute of an client- side image map |
5 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
vspace |
Sets or returns the white space on the top and bottom of the image |
4 |
1 |
9 |
Yes |
|||||
|
|
|||||||||
width |
Sets or returns the width of an image |
4 |
1 9 |
Yes |
||||||
Standard Properties
Property |
Description |
IE |
F |
O |
W3C |
className |
Sets or returns the class attribute of an element |
5 |
1 |
9 |
Yes |
title |
Sets or returns an element's advisory title |
5 |
1 |
9 |
Yes |
Area Object
The Area object represents an area of an image-map (An image-map is an image with clickable regions). For each instance of an <area> tag in an HTML document, an Area object is created.
IE: Internet Explorer, F: Firefox, O: Opera, W3C: World Wide Web Consortium (Internet Standard).
Area Object Properties
Property |
Description |
IE |
F |
O |
W3C |
||
accessKey |
Sets or returns the keyboard key to access an area |
5 |
1 |
No |
Yes |
||
alt |
Sets or returns an alternate text to be displayed, if a browser cannot show an area |
5 |
1 |
9 |
Yes |
||
|
|
||||||
coords |
Sets or returns the coordinates of a clickable area in an image- map |
5 |
1 |
9 |
Yes |
||
|
|
||||||
hash |
Sets or returns the anchor part of the URL in an area |
4 |
1 |
No |
No |
||
host |
Sets or returns the hostname and port of the URL in an area |
4 |
1 |
No |
No |
||
href |
Sets or returns the URL of a link in an image-map |
4 |
1 |
9 |
Yes |
||
id |
Sets or returns the id of an area |
4 |
1 |
9 |
Yes |
||
noHref |
Sets or returns whether an area should be active or inactive |
5 |
1 |
9 |
Yes |
||
pathname |
Sets or returns the pathname of the URL in an area |
4 |
1 |
9 |
No |
||
protocol |
Sets or returns the protocol of the URL in an area |
4 |
1 |
9 |
No |
||
search |
Sets or returns the query string part of the URL in an area |
4 |
1 |
9 |
No |
||
shape |
Sets or returns the shape of an area in an image-map |
5 |
1 |
9 |
Yes |
||
tabIndex |
Sets or returns the tab order for an area |
5 |
1 |
9 |
Yes |
||
target |
Sets or returns where to open the link-URL in an area |
4 |
1 9 |
Yes |
|||
Standard Properties
Property |
Description |
IE |
F |
O |
W3C |
className |
Sets or returns the class attribute of an element |
5 |
1 |
9 |
Yes |
dir |
Sets or returns the direction of text |
5 |
1 |
9 |
Yes |
lang |
Sets or returns the language code for an element |
5 |
1 |
9 |
Yes |
title |
Sets or returns an element's advisory title |
5 |
1 |
9 |
Yes |
Navigator Object
The Navigator object is actually a JavaScript object, not an HTML DOM object.
The Navigator object is automatically created by the JavaScript runtime engine and contains information about the client browser.
IE: Internet Explorer, F: Firefox, O: Opera.
Navigator Object Collections
Collection |
Description |
IE |
F |
O |
plugins[] |
Returns a reference to all embedded objects in the document |
4 |
1 9 |
Navigator Object Properties
Property |
Description |
IE |
F |
O |
|||
appCodeName |
Returns the code name of the browser |
4 |
1 |
9 |
|||
appMinorVersion |
Returns the minor version of the browser |
4 |
No |
No |
|||
appName |
Returns the name of the browser |
4 |
1 |
9 |
|||
appVersion |
Returns the platform and version of the browser |
4 |
1 |
9 |
|||
browserLanguage |
Returns the current browser language |
4 |
No |
9 |
|||
cookieEnabled |
Returns a Boolean value that specifies whether cookies are enabled in the browser |
4 |
1 |
9 |
|||
|
|
||||||
cpuClass |
Returns the CPU class of the browser's system |
4 |
No |
No |
|||
onLine |
Returns a Boolean value that specifies whether the system is in offline mode |
4 |
No |
No |
|||
|
|
||||||
platform |
Returns the operating system platform |
4 |
1 |
9 |
|||
systemLanguage |
Returns the default language used by the OS |
4 |
No |
No |
|||
userAgent |
Returns the value of the user-agent header sent by the client to the server |
4 |
1 |
9 |
|||
|
|
||||||
userLanguage |
Returns the OS' natural language setting |
4 |
No 9 |
||||
Navigator Object Methods
Method |
Description |
IE |
F |
O |
javaEnabled() |
Specifies whether or not the browser has Java enabled |
4 |
1 |
9 |
taintEnabled() |
Specifies whether or not the browser has data tainting enabled |
4 |
1 9 |
ZIP CODE VALIDATION
<!-- TWO STEPS TO INSTALL ZIP CODE VALIDATION:
1. Copy the coding into the HEAD of your HTML document
2. Add the last code into the BODY of your HTML document -->
<!-- STEP ONE: Paste this code into the HEAD of your HTML document -->
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- Original: Brian Swalwell -->
<!-- This script and many more are available free online at -->
<!-- The JavaScript Source!! http://javascript.internet.com -->
<!-- Begin
function validateZIP(field) { var valid = "0123456789-"; var hyphencount = 0;
if (field.length!=5 && field.length!=10) {
alert("Please enter your 5 digit or 5 digit+4 zip code."); return false;
}
for (var i=0; i < field.length; i++) { temp = "" + field.substring(i, i+1); if (temp == "-") hyphencount++;
if (valid.indexOf(temp) == "-1") {
alert("Invalid characters in your zip code. Please try again."); return false;
}
if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345- 6789'. Please try again.");
return false;
}
}
return true;
}
// End -->
</script>
</HEAD>
<!-- STEP TWO: Copy this code into the BODY of your HTML document -->
<BODY>
<center>
<form name=zip onSubmit="return validateZIP(this.zip.value)"> Zip: <input type=text size=30 name=zip>
<input type=submit value="Submit">
</form>
</center>
<p><center>
<font face="arial, helvetica" size="-2">Free JavaScripts provided<br>
by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>
Cookies:
A cookie is a piece of data from a website that is stored within a web browser that the website can retrieve at a later time. Cookies are used to tell the server that users have returned to a particular website. Cookies are text files with small pieces of data — like a username and password — that are used to identify your computer as you use a network. Specific cookies are used to identify specific users and improve their web browsing experience.
How to create a cookie?
With JavaScript, a cookie can be created like this:
document.cookie = "username=Sam";
You can also add an expiry date (in UTC time).
document.cookie = "username=Sam";
expires=Sun, 16 JAN 2022 12:00:00 UTC;
Example:
<!DOCTYPE html>
<html>
<body>
<form name="myform" action="">
Enter name:
<input type="text" name="customer" />
<input type="button" value="Set Cookie"
onclick="WriteCookie();" />
</form>
<script type="text/javascript">
function WriteCookie() {
if (document.myform.customer.value == "") {
alert("Please enter value");
return;
}
cookievalue = escape(
document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write("Setting Cookies : "
+ "name=" + cookievalue);
}
</script>
</body>
</html
Deleting the Cookie: When you want to delete the cookie just simply set the expires parameter and leave the username blank.
document.cookie = "username=;
expires=Sun, 16 JAN 2022 12:00:00 UTC";
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It runs inside the browser so, secured and works at client side. It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os etc.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass of Component. The class Component is the abstract base class for the non-menu user-interface controls of AWT. A component represents an object with graphical representation. The class Container is the super class for the containers of AWT. The container object can contain other AWT components.
Lifecycle of Java Applet
- Applet is initialized. init()
- Applet is started. start()
- Applet is painted. paint()
- Applet is stopped. stop()
- Applet is destroyed. destroy()
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of applet.
- public void init(): is used to initialized the Applet. It is invoked only once.
- public void start(): is invoked after the init() method or browser is maximized. It is used to start the Applet.
- public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is minimized.
- public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
- public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can be used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software.
How to run an Applet?
There are two ways to run an applet
- By html file.
- By appletViewer tool (for testing purpose).
Simple example of Applet by html file:
To execute the applet by html file, create an applet and compile it. After that create an html file and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:
To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
Unit 5 – Client Server Programming
Client-Server programming In Java: Java Socket, Java RMI. Threats: Malicious code-viruses, Trojan horses, worms; eavesdropping, spoofing, modification, denial of service attacks. Network security techniques: Password and Authentication; VPN, IP Security, security in electronic transaction, Secure Socket Layer (SSL), Secure Shell (SSH). Firewall: Introduction, Packet filtering, Stateful, Application layer, Proxy.
Internet Telephony: Introduction, VoIP. Multimedia Applications: Multimedia over IP: RSVP, RTP, RTCP and RTSP. Streaming media, Codec and Plugins, IPTV. mywbut.com Search Engine and Web Crawler: Definition, Meta data, Web Crawler, Indexing, Page rank, overview of SEO.
A socket is one endpoint of a two-way communication link between two programs running on the network. The socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent. In java socket programming example tutorial, we will learn how to write java socket server and java socket client program. We will also learn how server client program read and write data on the socket. java.net.Socket and java.net.ServerSocket are the java classes that implements Socket and Socket server.
package com.journaldev.socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.ClassNotFoundException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* This class implements java Socket server
* @author pankaj
*
*/
public class SocketServerExample {
//static ServerSocket variable
private static ServerSocket server;
//socket server port on which it will listen
private static int port = 9876;
public static void main(String args[]) throws IOException, ClassNotFoundException{
//create the socket server object
server = new ServerSocket(port);
//keep listens indefinitely until receives 'exit' call or program terminates
while(true){
System.out.println("Waiting for the client request");
//creating socket and waiting for client connection
Socket socket = server.accept();
//read from socket to ObjectInputStream object
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//convert ObjectInputStream object to String
String message = (String) ois.readObject();
System.out.println("Message Received: " + message);
//create ObjectOutputStream object
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//write object to Socket
oos.writeObject("Hi Client "+message);
//close resources
ois.close();
oos.close();
socket.close();
//terminate the server if client sends exit request
if(message.equalsIgnoreCase("exit")) break;
}
System.out.println("Shutting down Socket server!!");
//close the ServerSocket object
server.close();
}
}
Java Socket Client
package com.journaldev.socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* This class implements java socket client
* @author pankaj
*
*/
public class SocketClientExample {
public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException{
//get the localhost IP address, if server is running on some other IP, you need to use that
InetAddress host = InetAddress.getLocalHost();
Socket socket = null;
ObjectOutputStream oos = null;
ObjectInputStream ois = null;
for(int i=0; i<5;i++){
//establish socket connection to server
socket = new Socket(host.getHostName(), 9876);
//write to socket using ObjectOutputStream
oos = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Sending request to Socket Server");
if(i==4)oos.writeObject("exit");
else oos.writeObject(""+i);
//read the server response message
ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message: " + message);
//close resources
ois.close();
oos.close();
Thread.sleep(100);
}
}
}
To test java socket programming of server-client communication, first we
need to run SocketServerExample
class.
When you will run socket server, it will just print “Waiting for client
request” and then wait for the client request. Now when you will run
SocketClientExample class, it will send a request to java socket server and
print the response message to console. Here is the output of java socket server
SocketServerExample
program.
Waiting for the client request
Message Received: 0
Waiting for the client request
Message Received: 1
Waiting for the client request
Message Received: 2
Waiting for the client request
Message Received: 3
Waiting for the client request
Message Received: exit
Shutting down Socket server!!
Here is the output of Java socket client SocketClientExample
program.
Sending request to Socket Server
Message: Hi Client 0
Sending request to Socket Server
Message: Hi Client 1
Sending request to Socket Server
Message: Hi Client 2
Sending request to Socket Server
Message: Hi Client 3
Sending request to Socket Server
Message: Hi Client exit
Java RMI
The Java Remote Method Invocation (RMI) application programming interface (API) enables client and server communications over the net. Typically, client programs send requests to a server program, and the server program responds to those requests.
A common example is sharing a word processing program over a network. The word processor is installed on a server, and anyone who wants to use it starts it from his or her machine by double clicking an icon on the desktop or typing at the command line. The invocation sends a request to a server program for acess to the software, and the server program responds by making the software available to the requestor.
The RMI API lets you create a publicly accessible remote server object that enables client and server communications through simple method calls on the server object. Clients can easily communicate directly with the server object and indirectly with each other through the server object using Uniform Resource Locators (URLs) and HyperText Transfer Protocol (HTTP).
Comments
Post a Comment