Table Of ContentTCP/IP Sockets in Java
Second Edition
The Morgan Kaufmann Practical Guides Series
Series Editor: Michael J. Donahoo
TCP/IPSocketsinJava:PracticalGuideforProgrammers,SecondEdition
KennethL.CalvertandMichaelJ.Donahoo
SQL:PracticalGuideforDevelopers
MichaelJ.DonahooandGregorySpeegle
C#2.0:PracticalGuideforProgrammers
MicheldeChamplainandBrianPatrick
Multi-TierApplicationProgrammingwithPHP:PracticalGuideforArchitectsandProgrammers
DavidWall
TCP/IPSocketsinC#:PracticalGuideforProgrammers
DavidMakofske,MichaelJ.Donahoo,andKennethL.Calvert
JavaCryptographyExtensions:PracticalGuideforProgrammers
JasonWeiss
JSP:PracticalGuideforProgrammers
RobertBrunner
JSTL:PracticalGuideforJSPProgrammers
SueSpielman
Java:PracticalGuideforProgrammers
MichaelSikora
MulticastSockets:PracticalGuideforProgrammers
DavidMakofskeandKevinAlmeroth
TheStrutsFramework:PracticalGuideforJavaProgrammers
SueSpielman
TCP/IPSocketsinC:PracticalGuideforProgrammers
KennethL.CalvertandMichaelJ.Donahoo
JDBC:PracticalGuideforJavaProgrammers
GregorySpeegle
Forfurtherinformationonthesebooksandforalistofforthcomingtitles,
pleasevisitourWebsiteathttp://www.mkp.com.
TCP/IP Sockets in Java
Practical Guide for Programmers
Second Edition
Kenneth L. Calvert
UniversityofKentucky
Michael J. Donahoo
BaylorUniversity
AMSTERDAM•BOSTON•HEIDELBERG•LONDON
NEWYORK•OXFORD•PARIS•SANDIEGO
SANFRANCISCO•SINGAPORE•SYDNEY•TOKYO
MorganKaufmannPublishersisanimprintofElsevier
PublishingDirector JoanneTracy
Publisher DeniseE.M.Penrose
AcquisitionsEditor RickAdams
PublishingServicesManager GeorgeMorrison
SeniorProductionEditor DawnmarieSimpson
AssistantEditor MicheleCronin
ProductionAssistant LianneHong
CoverDesign AlisaAndreola
CoverImages istock
Composition diacriTech
TechnicalIllustration diacriTech
Copyeditor JCPublishing
Proofreader JanetCocker
Indexer JoanGreen
Interiorprinter SheridanBooks,Inc
Coverprinter PhoenixColor,Inc
MorganKaufmannPublishersisanimprintofElsevier.
30CorporateDrive,Suite400,Burlington,MA01803,USA
Thisbookisprintedonacid-freepaper.
©2008byElsevierInc.Allrightsreserved.ReproducedwithpermissionfromTCP/IP.
Designationsusedbycompaniestodistinguishtheirproductsareoftenclaimedastrademarksorregistered
trademarks.InallinstancesinwhichMorganKaufmannPublishersisawareofaclaim,theproductnames
appearininitialcapitalorallcapitalletters.Readers,however,shouldcontacttheappropriatecompaniesfor
morecompleteinformationregardingtrademarksandregistration.
Nopartofthispublicationmaybereproduced,storedinaretrievalsystem,ortransmittedinanyformorby
anymeans—electronic,mechanical,photocopying,scanning,orotherwise—withoutpriorwrittenpermissionof
thepublisher.
PermissionsmaybesoughtdirectlyfromElsevier’sScience&TechnologyRightsDepartmentinOxford,
UK:phone:(+44)1865843830,fax:(+44)1865853333,E-mail:[email protected]
completeyourrequestonlineviatheElsevierhomepage(http://elsevier.com),byselecting“Support&Contact”
then“CopyrightandPermission”andthen“ObtainingPermissions.”
LibraryofCongressCataloging-in-PublicationData
Calvert,KennethL.
TCP/IPsocketsinJava:practicalguideforprogrammers/KennethL.Calvert,MichaelJ.
Donahoo.–2nded.
p.cm.
Includesbibliographicalreferencesandindex.
ISBN978-0-12-374255-1(pbk.:alk.paper)1.Internetprogramming.2.TCP/IP(Computernetwork
protocol)3.Java(Computerprogramlanguage)I.Donahoo,MichaelJ.II.Title.
QA76.625.C352008
005.13(cid:2)3–dc22
2007039444
ISBN:978-0-12-374255-1
ForinformationonallMorganKaufmannpublications,
visitourWebsiteatwww.mkp.comorwww.books.elsevier.com
PrintedintheUnitedStates
08 09 10 11 12 5 4 3 2 1
To Tricia and Lisa
Thispageintentionallyleftblank
Contents
Preface xi
1 Introduction 1
1.1 Networks,Packets,andProtocols 1
1.2 AboutAddresses 4
1.3 AboutNames 6
1.4 ClientsandServers 6
1.5 WhatIsaSocket? 7
1.6 Exercises 8
2 BasicSockets 9
2.1 SocketAddresses 9
2.2 TCPSockets 15
2.2.1 TCPClient 16
2.2.2 TCPServer 21
2.2.3 InputandOutputStreams 25
2.3 UDPSockets 26
2.3.1 DatagramPacket 27
2.3.2 UDPClient 29
2.3.3 UDPServer 34
2.3.4 SendingandReceivingwithUDPSockets 36
2.4 Exercises 38
3 SendingandReceivingData 39
3.1 EncodingInformation 40
3.1.1 PrimitiveIntegers 40
vii
viii
Contents
3.1.2 StringsandText 45
3.1.3 Bit-Diddling:EncodingBooleans 47
3.2 ComposingI/OStreams 48
3.3 FramingandParsing 49
3.4 Java-SpecificEncodings 55
3.5 ConstructingandParsingProtocolMessages 55
3.5.1 Text-BasedRepresentation 58
3.5.2 BinaryRepresentation 61
3.5.3 SendingandReceiving 63
3.6 WrappingUp 71
3.7 Exercises 71
4 BeyondtheBasics 73
4.1 Multitasking 73
4.1.1 JavaThreads 74
4.1.2 ServerProtocol 76
4.1.3 Thread-per-Client 80
4.1.4 ThreadPool 82
4.1.5 System-ManagedDispatching:TheExecutorInterface 84
4.2 BlockingandTimeouts 86
4.2.1 accept(),read(),andreceive() 87
4.2.2 ConnectingandWriting 87
4.2.3 LimitingPer-ClientTime 87
4.3 MultipleRecipients 89
4.3.1 Broadcast 90
4.3.2 Multicast 90
4.4 ControllingDefaultBehaviors 95
4.4.1 Keep-Alive 96
4.4.2 SendandReceiveBufferSize 96
4.4.3 Timeout 97
4.4.4 AddressReuse 97
4.4.5 EliminatingBufferingDelay 98
4.4.6 UrgentData 98
4.4.7 LingeringafterClose 99
4.4.8 BroadcastPermission 99
4.4.9 TrafficClass 100
4.4.10 Performance-BasedProtocolSelection 100
4.5 ClosingConnections 101
4.6 Applets 107
4.7 WrappingUp 107
4.8 Exercises 108
5 NIO 109
5.1 WhyDoWeNeedThis? 109
5.2 UsingChannelswithBuffers 112
ix
Contents
5.3 Selectors 115
5.4 BuffersinDetail 121
5.4.1 BufferIndices 121
5.4.2 BufferCreation 122
5.4.3 StoringandRetrievingData 124
5.4.4 PreparingBuffers:clear(),flip(),andrewind() 126
5.4.5 CompactingDatainaBuffer 128
5.4.6 BufferPerspectives:duplicate(),slice(),etc. 129
5.4.7 CharacterCoding 131
5.5 Stream(TCP)ChannelsinDetail 132
5.6 SelectorsinDetail 135
5.6.1 RegisteringInterestinChannels 135
5.6.2 SelectingandIdentifyingReadyChannels 138
5.6.3 ChannelAttachments 140
5.6.4 SelectorsinaNutshell 140
5.7 Datagram(UDP)Channels 141
5.8 Exercises 145
6 UndertheHood 147
6.1 BufferingandTCP 150
6.2 DeadlockDanger 152
6.3 PerformanceImplications 155
6.4 TCPSocketLifeCycle 155
6.4.1 Connecting 156
6.4.2 ClosingaTCPConnection 160
6.5 DemultiplexingDemystified 163
6.6 Exercises 165
Bibliography 167
Index 169