•
•
•
•
•
•
TableofContents
Index
Reviews
ReaderReviews
Errata
Academic
JavaNetworkProgramming,3rdEdition
ByElliotteRustyHarold
Publisher :O'Reilly
PubDate :October2004
ISBN :0-596-00721-3
Pages :706
Thoroughlyrevisedtocoverallthe100+
significantupdatestoJavaDevelopersKit
(JDK)1.5,JavaNetworkProgrammingisa
completeintroductiontodevelopingnetwork
programs(bothappletsandapplications)
usingJava,coveringeverythingfrom
networkingfundamentalstoremotemethod
invocation(RMI).ItincludeschaptersonTCP
andUDPsockets,multicastingprotocoland
contenthandlers,servlets,andthenewI/O
API.Thisistheessentialresourceforany
seriousJavadeveloper.
•
•
•
•
•
•
TableofContents
Index
Reviews
ReaderReviews
Errata
Academic
JavaNetworkProgramming,3rdEdition
ByElliotteRustyHarold
Publisher :O'Reilly
PubDate :October2004
ISBN :0-596-00721-3
Pages :706
Copyright
Preface
AbouttheThirdEdition
OrganizationoftheBook
WhoYouAre
AbouttheExamples
RequestforComments
JavaVersions
ConventionsUsedinThisBook
CommentsandQuestions
Acknowledgments
Chapter1.WhyNetworkedJava?
Section1.1.WhatCanaNetworkProgramDo?
Section1.2.Security
Section1.3.ButWait!There'sMore!
Chapter2.BasicNetworkConcepts
Section2.1.Networks
Section2.2.TheLayersofaNetwork
Section2.3.IP,TCP,andUDP
Section2.5.TheClient/ServerModel
Section2.4.TheInternet
Section2.6.InternetStandards
Chapter3.BasicWebConcepts
Section3.1.URIs
Section3.2.HTML,SGML,andXML
Section3.3.HTTP
Section3.4.MIMEMediaTypes
Section3.5.Server-SidePrograms
Chapter4.Streams
Section4.1.OutputStreams
Section4.2.InputStreams
Section4.3.FilterStreams
Section4.4.ReadersandWriters
Chapter5.Threads
Section5.1.RunningThreads
Section5.2.ReturningInformationfromaThread
Section5.4.Deadlock
Section5.3.Synchronization
Section5.5.ThreadScheduling
Section5.6.ThreadPools
Chapter6.LookingUpInternetAddresses
Section6.1.TheInetAddressClass
Section6.2.Inet4AddressandInet6Address
Section6.3.TheNetworkInterfaceClass
Section6.4.SomeUsefulPrograms
Chapter7.URLsandURIs
Section7.1.TheURLClass
Section7.2.TheURLEncoderandURLDecoderClasses
Section7.4.Proxies
Section7.3.TheURIClass
Section7.5.CommunicatingwithServer-SideProgramsThroughGET
Section7.6.AccessingPassword-ProtectedSites
Chapter8.HTMLinSwing
Section8.1.HTMLonComponents
Section8.2.JEditorPane
Section8.3.ParsingHTML
Section8.4.Cookies
Chapter9.SocketsforClients
Section9.1.SocketBasics
Section9.2.InvestigatingProtocolswithTelnet
Section9.3.TheSocketClass
Section9.5.SocketAddresses
Section9.4.SocketExceptions
Section9.6.Examples
Chapter10.SocketsforServers
Section10.1.TheServerSocketClass
Section10.2.SomeUsefulServers
Chapter11.SecureSockets
Section11.1.SecureCommunications
Section11.2.CreatingSecureClientSockets
Section11.3.MethodsoftheSSLSocketClass
Section11.4.CreatingSecureServerSockets
Section11.5.MethodsoftheSSLServerSocketClass
Chapter12.Non-BlockingI/O
Section12.1.AnExampleClient
Section12.2.AnExampleServer
Section12.4.Channels
Section12.3.Buffers
Section12.5.ReadinessSelection
Chapter13.UDPDatagramsandSockets
Section13.1.TheUDPProtocol
Section13.2.TheDatagramPacketClass
Section13.3.TheDatagramSocketClass
Section13.4.SomeUsefulApplications
Section13.5.DatagramChannel
Chapter14.MulticastSockets
Section14.1.WhatIsaMulticastSocket?
Section14.2.WorkingwithMulticastSockets
Section14.3.TwoSimpleExamples
Chapter15.URLConnections
Section15.1.OpeningURLConnections
Section15.2.ReadingDatafromaServer
Section15.3.ReadingtheHeader
Section15.5.ConfiguringtheClientRequestHTTPHeader
Section15.4.ConfiguringtheConnection
Section15.6.WritingDatatoaServer
Section15.8.TheObjectMethods
Section15.10.GuessingMIMEContentTypes
Section15.12.Caches
Section15.7.ContentHandlers
Section15.9.SecurityConsiderationsforURLConnections
Section15.11.HttpURLConnection
Section15.13.JarURLConnection
Chapter16.ProtocolHandlers
Section16.1.WhatIsaProtocolHandler?
Section16.2.TheURLStreamHandlerClass
Section16.3.WritingaProtocolHandler
Section16.4.MoreProtocolHandlerExamplesandTechniques
Section16.5.TheURLStreamHandlerFactoryInterface
Chapter17.ContentHandlers
Section17.1.WhatIsaContentHandler?
Section17.2.TheContentHandlerClass
Section17.3.TheContentHandlerFactoryInterface
Section17.4.AContentHandlerfortheFITSImageFormat
Chapter18.RemoteMethodInvocation
Section18.1.WhatIsRemoteMethodInvocation?
Section18.2.Implementation
Section18.4.Thejava.rmiPackage
Section18.3.LoadingClassesatRuntime
Section18.5.Thejava.rmi.registryPackage
Section18.6.Thejava.rmi.serverPackage
Chapter19.TheJavaMailAPI
Section19.1.WhatIstheJavaMailAPI?
Section19.2.SendingEmail
Section19.4.PasswordAuthentication
Section19.6.TheURLNameClass
Section19.8.ThePartInterface
Section19.10.MIMEMessages
Section19.3.ReceivingMail
Section19.5.Addresses
Section19.7.TheMessageClass
Section19.9.MultipartMessagesandFileAttachments
Section19.11.Folders
Colophon
Index
Copyright©2005,2000,1997O'ReillyMedia,Inc.Allrights
reserved.
PrintedintheUnitedStatesofAmerica.
PublishedbyO'ReillyMedia,Inc.,1005GravensteinHighway
North,Sebastopol,CA95472.
O'Reillybooksmaybepurchasedforeducational,business,or
salespromotionaluse.Onlineeditionsarealsoavailablefor
mosttitles().Formoreinformation,
contactourcorporate/institutionalsalesdepartment:(800)
998-9938or
NutshellHandbook,theNutshellHandbooklogo,andthe
O'ReillylogoareregisteredtrademarksofO'ReillyMedia,Inc.
Java™NetworkProgramming,ThirdEdition,theimageofa
riverotter,andrelatedtradedressaretrademarksofO'Reilly
Media,Inc.
Java™andallJava-basedtrademarksandlogosaretrademarks
orregisteredtrademarksofSunMicrosystems,Inc.,inthe
UnitedStatesandothercountries.O'ReillyMedia,Inc.is
independentofSunMicrosystems.
Manyofthedesignationsusedbymanufacturersandsellersto
distinguishtheirproductsareclaimedastrademarks.Where
thosedesignationsappearinthisbook,andO'ReillyMedia,Inc.
wasawareofatrademarkclaim,thedesignationshavebeen
printedincapsorinitialcaps.
Whileeveryprecautionhasbeentakeninthepreparationofthis
book,thepublisherandauthorassumenoresponsibilityfor
errorsoromissions,orfordamagesresultingfromtheuseof
theinformationcontainedherein.
Preface
Java'sgrowthoverthelast10yearshasbeennothingshortof
phenomenal.GivenJava'srapidrisetoprominenceandthe
evenmorespectaculargrowthoftheInternet,it'salittle
surprisingthatnetworkprogramminginJavaisstillso
mysterioustosomany.Itdoesn'thavetobe.Infact,writing
networkprogramsinJavaisquitesimple,asthisbookwill
show.Readerswithpreviousexperienceinnetwork
programminginaUnix,Windows,orMacintoshenvironment
shouldbepleasantlysurprisedathowmucheasieritistowrite
equivalentprogramsinJava.TheJavacoreAPIincludeswelldesignedinterfacestomostnetworkfeatures.Indeed,thereis
verylittleapplication-layernetworksoftwareyoucanwriteinC
orC++thatyoucan'twritemoreeasilyinJava.JavaNetwork
Programming,3rdEditionendeavorstoshowyouhowtotake
advantageofJava'snetworkclasslibrarytoquicklyandeasily
writeprogramsthataccomplishmanycommonnetworking
tasks.Someoftheseinclude:
BrowsingtheWebwithHTTP
ParsingandrenderingHTML
SendingemailwithSMTP
ReceivingemailwithPOPandIMAP
Writingmultithreadedservers
Installingnewprotocolandcontenthandlersintobrowsers
Encryptingcommunicationsforconfidentiality,
authentication,andguaranteedmessageintegrity
DesigningGUIclientsfornetworkservices
Postingdatatoserver-sideprograms
LookinguphostsusingDNS
DownloadingfileswithanonymousFTP
Connectingsocketsforlow-levelnetworkcommunication
Distributingapplicationsacrossmultiplesystemswith
RemoteMethodInvocation
Javaisthefirstlanguagetoprovidesuchapowerfulcrossplatformnetworklibrary,whichhandlesallthesediversetasks.
JavaNetworkProgrammingexposesthepowerand
sophisticationofthislibrary.Thisbook'sgoalistoenableyouto
startusingJavaasaplatformforseriousnetwork
programming.Todoso,thisbookprovidesageneral
backgroundinnetworkfundamentals,aswellasdetailed
discussionsofJava'sfacilitiesforwritingnetworkprograms.
You'lllearnhowtowriteJavaprogramsthatsharedataacross
theInternetforgames,collaboration,softwareupdates,file
transfer,andmore.You'llalsogetabehind-the-sceneslookat
HTTP,SMTP,TCP/IP,andtheotherprotocolsthatsupportthe
InternetandtheWeb.Whenyoufinishthisbook,you'llhave
theknowledgeandthetoolstocreatethenextgenerationof
softwarethattakesfulladvantageoftheInternet.
AbouttheThirdEdition
In1996,inthefirstchapterofthefirsteditionofthisbook,I
wroteextensivelyaboutthesortofdynamic,distributed
networkapplicationsIthoughtJavawouldmakepossible.One
ofthemostexcitingpartsofwritingsubsequenteditionshas
beenseeingvirtuallyalloftheapplicationsIforetoldcometo
pass.ProgrammersareusingJavatoquerydatabaseservers,
monitorwebpages,controltelescopes,managemultiplayer
games,andmore,allbyusingJava'snativeabilitytoaccessthe
Internet.JavaingeneralandnetworkprogramminginJavain
particularhasmovedwellbeyondthehypestageandintothe
realmofreal,workingapplications.Notallnetworksoftwareis
yetwritteninJava,butit'snotforalackoftrying.Effortsare
wellunderwaytosubverttheexistinginfrastructureofC-based
networkclientsandserverswithpureJavareplacements.
ClientsfornewerprotocolslikeGnutellaandFreenetare
preferentiallywritteninJava.It'sunlikelythatJavawillreplace
Cforallnetworkprogramminginthenearfuture.However,the
merefactthatmanypeoplearewillingtousewebbrowsers,
webservers,andmorewritteninJavashowsjusthowfarwe've
comesince1996.
Thisbookhascomealongway,too.Thethirdeditionhasone
completelynewchaptertodescribethemostsignificant
developmentinnetworkprogrammingsincereadersandwriters
wereintroducedinJava1.1.IreferofcoursetothenewI/O
APIsinthejava.niopackage.Theabilitytoperform
asynchronous,non-blockingI/Ooperationsiscriticalforhighperformancenetworkapplications,especiallyservers.It
removesoneofthelastbarrierstousingJavafornetwork
servers.Manyotherchaptershavebeenupdatedtotake
advantageofthesenewI/OAPIs.
There'vebeenlotsofothersmallchangesandupdates
throughoutthejava.netandsupportingpackagesinJava1.4
and1.5,andthesearecoveredhereaswell.Newclasses
addressedinthiseditionincludeCookieHandler,
SocketAddress,Proxy,NetworkInterface,andURI.IPv6has
becomeareality,andisnowcoveredextensively.Manyother
methodshavebeenaddedtoexistingclassesinthelasttwo
releasesofJava,andthesearediscussedintherelevant
chapters.I'vealsorewrittenlargepartsofthebooktoreflect
changingfashionsinJavaprogrammingingeneralandnetwork
programminginparticular.AppletsandCGIprogramsare
emphasizedmuchless.Intheirplace,you'llfindmoregeneric
discussionofremotecodeexecutionandserver-side
environments,howeverimplemented.
Ofcourse,thetexthasbeencleanedup,too.There'sonlyone
completelynewchapterhere,butthe18existingchaptershave
beenextensivelyrewrittenandexpandedtobringthemup-todatewithnewdevelopmentsaswellastomakethemclearer
andmoreengaging.Ihopeyou'llfindthisthirdeditionaneven
stronger,longer-lived,moreaccurate,andmoreenjoyable
tutorialandreferencetonetworkprogramminginJavathanthe
lastedition.
OrganizationoftheBook
Thisbookbeginswiththreechaptersthatoutlinehownetworks
andnetworkprogramswork.Chapter1,isagentleintroduction
tonetworkprogramminginJavaandtheapplicationsitmakes
possible.Allreadersshouldfindsomethingofinterestinthis
chapter.Itexploressomeoftheuniqueprogramsthatbecome
feasiblewhennetworkingiscombinedwithJava.Chapter2,and
Chapter3,explainindetailwhataprogrammerneedstoknow
abouthowtheInternetandtheWebwork.Chapter2describes
theprotocolsthatunderlietheInternet,suchasTCP/IPand
UDP/IP.Chapter3describesthestandardsthatunderliethe
Web,suchasHTTP,HTML,andREST.Ifyou'vedonealotof
networkprogramminginotherlanguagesonotherplatforms,
youmaybeabletoskipthesetwochapters.
ThenexttwochaptersthrowsomelightontwopartsofJava
programmingthatarecriticaltoalmostallnetworkprograms
butareoftenmisunderstoodandmisused,I/Oandthreading.
Chapter4,exploresJava'sclassicI/Omodelswhich,despitethe
newI/OAPIs,aren'tgoingawayanytimesoonandarestillthe
preferredmeansofhandlinginputandoutputinmostclient
applications.UnderstandinghowJavahandlesI/Ointhegeneral
caseisaprerequisiteforunderstandingthespecialcaseofhow
JavahandlesnetworkI/O.Chapter5,exploresmultithreading
andsynchronization,withaspecialemphasisonhowtheycan
beusedforasynchronousI/Oandnetworkservers.Experienced
Javaprogrammersmaybeabletoskimorskipthesetwo
chapters.However,Chapter6,isessentialreadingforeveryone.
ItshowshowJavaprogramsinteractwiththedomainname
systemthroughtheInetAddressclass,theoneclassthat's
neededbyessentiallyallnetworkprograms.Onceyou've
finishedthischapter,it'spossibletojumparoundinthebookas
yourinterestsandneedsdictate.Thereare,however,some
interdependenciesbetweenspecificchapters.FigureP-1should
allowyoutomapoutpossiblepathsthroughthebook.
FigureP-1.Chapterprerequisites
Chapter7,URLsandURIs,exploresJava'sURLclass,apowerful
abstractionfordownloadinginformationandfilesfromnetwork
serversofmanykinds.TheURLclassenablesyoutoconnectto
anddownloadfilesanddocumentsfromanetworkserver
withoutconcerningyourselfwiththedetailsoftheprotocolthe
serverspeaks.ItletsyouconnecttoanFTPserverusingthe
samecodeyouusetotalktoanHTTPserverortoreadafileon
thelocalharddisk.
Onceyou'vegotanHTMLfilefromaserver,you'regoingto
wanttodosomethingwithit.ParsingandrenderingHTMLis
oneofthemostdifficultchallengesnetworkprogrammerscan
face.Chapter8,introducessomelittleknownclassesfor
parsingandrenderingHTMLdocumentsthattakethisburden
offyourshouldersandputitonSun's.
Chapter9throughChapter11discussJava'slow-levelsocket
classesfornetworkaccess.Chapter9,introducestheJava
socketsAPIandtheSocketclassinparticular.Itshowsyou
howtowritenetworkclientsthatinteractwithTCPserversofall
kindsincludingwhois,finger,andHTTP.Chapter10,showsyou
howtousetheServerSocketclasstowriteserversforthese
andotherprotocolsinJava.Chapter11,showsyouhowto
protectyourclientservercommunicationsusingtheSecure
SocketsLayer(SSL)andtheJavaSecureSocketsExtension
(JSSE).
Chapter12,coversthenewI/OAPIsintroducedinJava1.4.
TheseAPIswerespecificallydesignedfornetworkservers.They
enableaprogramtofigureoutwhetheraconnectionisready
beforeittriestoreadfromorwritetothesocket.Thisallowsa
singlethreadtomanagemanydifferentconnections
simultaneously,therebyplacingmuchlessloadonthevirtual
machine.ThenewI/OAPIsdon'thelpmuchforsmallserversor
clientsthatdon'topenmanysimultaneousconnections,but
theyprovidehugeperformanceboostsforhighvolumeservers
thatwanttotransmitasmuchdataasthenetworkcanhandle
asfastasthenetworkcandeliverit.
Chapter13,introducestheUserDatagramProtocol(UDP)and
theassociatedDatagramPacketandDatagramSocketclasses
thatprovidefast,unreliablecommunication.Finally,Chapter14,
showsyouhowtouseUDPtocommunicatewithmultiplehosts
atthesametime.Alltheotherclassesthataccessthenetwork
fromJavarelyontheclassesdescribedinthesefivechapters.
Chapter15throughChapter17lookmoredeeplyatthe
infrastructuresupportingtheURLclass.Thesechapters
introduceprotocolandcontenthandlers,conceptsuniqueto
Javathatmakeitpossibletowritedynamicallyextensible
softwarethatautomaticallyunderstandsnewprotocolsand
mediatypes.Chapter15,describestheclassthatservesasthe
enginefortheURLclassofChapter7.Itshowsyouhowtotake
advantageofthisclassthroughitspublicAPI.Chapter16,also
focusesontheURLConnectionclassbutfromadifferent
direction;itshowsyouhowtosubclassthisclasstocreate
handlersfornewprotocolsandURLs.Finally,Chapter17,
exploresJava'ssomewhatmoribundmechanismforsupporting
newmediatypes.
Chapter18andChapter19introducetwouniquehigher-level
APIsfornetworkprograms,RemoteMethodInvocation(RMI)
andtheJavaMailAPI.Chapter18,introducesthispowerful
mechanismforwritingdistributedJavaapplicationsthatrun
acrossmultipleheterogeneoussystemsatthesametimewhile
communicatingwithstraightforwardmethodcallsjustlikea
nondistributedprogram.Chapter19,acquaintsyouwiththis
standardextensiontoJava,whichoffersanalternativetolowlevelsocketsfortalkingtoSMTP,POP,IMAP,andotheremail
servers.BothoftheseAPIsprovidedistributedapplicationswith
lesscumbersomealternativestolower-levelprotocols.
WhoYouAre
ThisbookassumesyouarecomfortablewiththeJavalanguage
andprogrammingenvironment,inadditiontoobject-oriented
programmingingeneral.Thisbookdoesnotattempttobea
basiclanguagetutorial.Youshouldbethoroughlyfamiliarwith
thesyntaxofJava.Youshouldhavewrittensimpleapplications
andapplets.YoushouldalsobecomfortablewithbasicAWTand
Swingprogramming.Whenyouencounteratopicthatrequires
adeeperunderstandingfornetworkprogrammingthanis
customaryforinstance,threadsandstreamsI'llcoverthattopic
aswell,atleastbriefly.
YoushouldalsobeanaccomplisheduseroftheInternet.Iwill
assumeyouknowhowtoFTPfilesandvisitwebsites.You
shouldknowwhataURLisandhowyoulocateone.Youshould
knowhowtowritesimpleHTMLandbeabletopublishahome
pagethatincludesJavaapplets,althoughyoudonotneedtobe
asuperwebdesigner.
However,thisbookdoesn'tassumethatyouhaveprior
experiencewithnetworkprogramming.Youshouldfindita
completeintroductiontonetworkingconceptsandnetwork
applicationdevelopment.Idon'tassumethatyouhaveafew
thousandnetworkingacronyms(TCP,UDP,SMTP,etc.)atthetip
ofyourtongue.You'lllearnwhatyouneedtoknowaboutthese
here.It'scertainlypossiblethatyoucouldusethisbookasa
generalintroductiontonetworkprogrammingwithasocket-like
interface,andthengoontolearnWSA(theWindowsSocket
Architecture)andfigureouthowtowritenetworkapplications
inC++.Butit'snotclearwhyyouwouldwantto:asIsaid
earlier,Javaletsyouwriteverysophisticatedapplicationswith
ease.
JavaVersions
Java'snetworkclasseshavechangedalotmoreslowlysince
Java1.0thanotherpartsofthecoreAPI.Incomparisontothe
AWTorI/O,therehavebeenalmostnochangesandonlyafew
additions.Ofcourse,allnetworkprogramsmakeextensiveuse
oftheI/OclassesandmanymakeheavyuseofGUIs.Thisbook
iswrittenwiththeassumptionthatyouandyourcustomersare
usingatleastJava1.1.Ingeneral,IuseJava1.1featureslike
readersandwritersandtheneweventmodelfreelywithout
furtherexplanation.
Java2isabitmoreofastretch.AlthoughIwrotealmostthis
entirebookusingJava2,andalthoughJava2hasbeen
availableformostplatformsforseveralyears,noJava2
runtimeordevelopmentenvironmentisyetavailableforMacOS
9.ItisvirtuallycertainthatneitherApplenorSunwilleverport
anyversionofJava2toMacOS9.xorearlier,thuseffectively
lockingout60%ofthecurrentMac-installedbasefromfuture
developments.Thisisnotagoodthingforalanguagethat
claimstobe"writeonce,runanywhere."Furthermore,
Microsoft'sJavavirtualmachinesupportsJava1.1onlyand
doesnotseemlikelytoimproveinthisrespectforthe
foreseeablefuture.Thus,whileIhavenotshiedawayfrom
usingJava2-specificfeatureswheretheyseemedusefulor
convenientforinstance,theASCIIencodingforthe
InputStreamReaderandthekeytoolprogramIhavebeen
carefultopointoutmyuseofsuchfeatures.Where1.1safe
alternativesexist,theyarenoted.Whenaparticularmethodor
classisnewinJava1.2orlater,itisnotedbyacomment
followingitsdeclarationlikethis:
publicvoidsetTimeToLive(intttl)throwsIOException//Java1
Tofurthermuddythewaters,therearemultipleversionsof
Java2.Atthetimethisbookwascompleted,thecurrent
releasewasthe"Java™2SDK,StandardEdition,v1.4.2_05".
Atleastthat'swhatitwascalledthen.Sunseemstochange
namesatthedropofamarketingconsultant.Inprevious
incarnations,thisiswhatwassimplyknownastheJDK.Sun
alsomakesavailablethe"Java™2Platform,EnterpriseEdition
(J2EE©)"and"Java™2Platform,MicroEdition(J2ME©)".The
EnterpriseEditionisasupersetofthestandardeditionthat
addsfeaturesliketheJavaNamingandDirectoryInterfaceand
theJavaMailAPIthatprovidehigh-levelAPIsfordistributed
applications.MostoftheseadditionalAPIsarealsoavailableas
extensionstothestandardedition,andwillbesotreatedhere.
TheMicroEditionisasubsetofthestandardeditiontargetedat
cellphones,set-topboxes,andothermemory,CPU,and
display-challengeddevices.ItremovesalotoftheGUIAPIs
programmershavelearnedtoassociatewithJava,although
surprisinglyitretainsmanyofthebasicnetworkingandI/O
classesdiscussedinthisbook.Finally,whenthisbookwas
abouthalfcomplete,Sunreleasedabetaofthe"Java™2SDK,
StandardEdition,v1.5".Thisaddedafewpiecestothe
networkingAPI,butleftmostoftheexistingAPIuntouched.
OverthenextfewmonthsSunreleasedseveralmorebetasof
JDK1.5.Thefinishingtoucheswereplacedonthisbookandall
thecodetestedwithJDK1.5beta2.Youshouldn'thaveany
troubleusingthisbookafter1.5isreleased.Withanyluckat
all,discrepanciesbetweenthefinalspecificationandwhatI
discussherewillbequiteminor.
Tobehonest,themostannoyingproblemwithallthese
differentversionsandeditionswasnottherewritingthey
necessitated.Itwasfiguringouthowtoidentifytheminthe
text.IsimplyrefusetowriteJava™2SDK,StandardEdition,
v1.3orevenJava21.3everytimeIwanttopointoutanew
featureinthelatestreleaseofJava.Inormallysimplyreferto
Java1.1,Java1.2,Java1.3,Java1.4,andJava1.5.Overall,
though,thenetworkingAPIseemsfairlystable.Java1.1
throughJava1.3areverysimilar,andthereareafewonly
majoradditionsinJava1.4and1.5.Verylittleofthepost-1.0
networkingAPIhasbeendeprecated.
AbouttheExamples
Mostmethodsandclassesdescribedinthisbookareillustrated
withatleastonecompleteworkingprogram,simplethoughit
maybe.Inmyexperience,acompleteworkingprogramis
essentialtoshowingtheproperuseofamethod.Withouta
program,itistooeasytodropintojargonortoglossover
pointsaboutwhichtheauthormaybeunclearinhisownmind.
TheJavaAPIdocumentationitselfoftensuffersfromexcessively
tersedescriptionsofthemethodcalls.Inthisbook,Ihavetried
toerronthesideofprovidingtoomuchexplicationratherthan
toolittle.Ifapointisobvioustoyou,feelfreetoskipoverit.
Youdonotneedtotypeinandruneveryexampleinthisbook,
butifaparticularmethoddoesgiveyoutrouble,youare
guaranteedtohaveatleastoneworkingexample.
Eachchapterincludesatleastone(andoftenseveral)more
complexprogramsthatdemonstratetheclassesandmethodsof
thatchapterinamorerealisticsetting.TheseoftenrelyonJava
featuresnotdiscussedinthisbook.Indeed,inmanyofthe
programs,thenetworkingcomponentsareonlyasmallfraction
ofthesourcecodeandoftentheleastdifficultparts.
Nonetheless,noneoftheseprogramscouldbewrittenaseasily
inlanguagesthatdidn'tgivenetworkingthecentralpositionit
occupiesinJava.Theapparentsimplicityofthenetworked
sectionsofthecodereflectstheextenttowhichnetworkinghas
beenmadeacorefeatureofJava,andnotanytrivialityofthe
programitself.Allexampleprogramspresentedinthisbookare
availableonline,oftenwithcorrectionsandadditions.Youcan
downloadthesourcecodefrom
/>ThisbookassumesyouareusingSun'sJavaDevelopmentKit.I
havetestedalltheexamplesonLinuxandmanyonWindows
andMacOSX.Almostalltheexamplesgivenhereshouldwork
onotherplatformsandwithothercompilersandvirtual
machinesthatsupportJava1.2(andmostonJava1.1,aswell).
TheoccasionalexamplesthatrequireJava1.3,1.4,or1.5are
clearlynoted.
ConventionsUsedinThisBook
BodytextisTimesRoman,normal,likeyou'rereadingnow.
Amonospacedtypewriterfontisusedfor:
Codeexamplesandfragments
AnythingthatmightappearinaJavaprogram,including
keywords,operators,datatypes,methodnames,variable
names,classnames,andinterfacenames
Programoutput
TagsthatmightappearinanHTMLdocument
Aboldmonospacedfontisusedfor:
Commandlinesandoptionsthatshouldbetypedverbatim
onthescreen
Anitalicizedfontisusedfor:
Newtermswheretheyaredefined
Pathnames,filenames,andprogramnames(however,ifthe
programnameisalsothenameofaJavaclass,itisgiven
inamonospacedfont,likeotherclassnames)
Hostanddomainnames(java.oreilly.com)
URLs( />
Titlesofotherchaptersandbooks(JavaI/O)
Significantcodefragmentsandcompleteprogramsare
generallyplacedintoaseparateparagraph,likethis:
Sockets=newSocket("java.oreilly.com",80);
if(!s.getTcpNoDelay())s.setTcpNoDelay(true);
Whencodeispresentedasfragmentsratherthancomplete
programs,theexistenceoftheappropriateimportstatements
shouldbeinferred.Forexample,intheabovecodefragment
youmayassumethatjava.net.Socketwasimported.
Someexamplesintermixuserinputwithprogramoutput.In
thesecases,theuserinputwillbedisplayedinbold,asinthis
examplefromChapter9:
%telnetrama.poly.edu7
Trying128.238.10.212...
Connectedtorama.poly.edu.
Escapecharacteris'^]'.
Thisisatest
Thisisatest
Thisisanothertest
Thisisanothertest
9876543210
9876543210
^]
telnet>close
Connectionclosed.
TheJavaprogramminglanguageiscase-sensitive.
Java.net.socketisnotthesameasjava.net.Socket.Casesensitiveprogramminglanguagesdonotalwaysallowauthors
toadheretostandardEnglishgrammar.Mostofthetime,it's
possibletorewritethesentenceinsuchawaythatthetwodo
notconflict,andwhenpossibleIhaveendeavoredtodoso.
However,onthoserareoccasionswhenthereissimplynoway
aroundtheproblem,IhaveletstandardEnglishcomeupthe
loser.Inkeepingwiththisprinciple,whenIwanttorefertoa
classoraninstanceofaclassinbodytext,Iusethe
capitalizationthatyou'dseeinsourcecode,generallyaninitial
capitalwithinternalcapitalizationforexample,ServerSocket.
Throughoutthisbook,IusetheBritishconventionofplacing
punctuationinsidequotationmarksonlywhenpunctuationis
partofthematerialquoted.AlthoughIlearnedgrammarunder
theAmericanrules,theBritishsystemhasalwaysseemedfar
morelogicaltome,evenmoresothanusualwhenonemust
quotesourcecodewhereamissingoraddedcomma,period,or
semicoloncanmakethedifferencebetweencodethatcompiles
andcodethatdoesn't.
Finally,althoughmanyoftheexamplesusedherearetoy
examplesunlikelytobereused,afewoftheclassesIdevelop
haverealvalue.Pleasefeelfreetoreusethemoranypartsof
theminyourowncode.Nospecialpermissionisrequired.As
farasIamconcerned,theyareinthepublicdomain(although
thesameismostdefinitelynottrueoftheexplanatorytext!).
Suchclassesareplacedsomewhereinthecom.macfaqpackage,
generallymirroringthejavapackagehierarchy.Forinstance,
Chapter4'sSafePrintWriterclassisinthecom.macfaq.io
package.Whenworkingwiththeseclasses,don'tforgetthatthe
compiled.classfilesmustresideindirectoriesmatchingtheir
packagestructureinsideyourclasspath,andthatyou'llhaveto
importtheminyourownclassesbeforeyoucanusethem.The
book'swebpageat />includesajarfilecontainingalltheseclassesthatcanbe
installedinyourclasspath.
Indicatesatip,suggestion,orgeneralnote.
Indicatesawarningorcaution.