java语言程序设计解答例题复习题答案30review.pdf
Chapter30Networking
1.YouusenewServerSocket(port)tocreateaserversocket.Youcanuse
anynumberafter1024.Ifaportisalreadyinuse,youwillgetanexception;then
youcanchooseanothernumber.Youcanhaveaserverrunningonaportserving
multipleclients.
2.Aserversocketcanhandleconnectionrequestsfromaclient.Afterthe
connectionisestablished,thecommunicationsbetweentheserverandtheclient
arethroughtheclientsockets.
3.TheclientprogramusesnewSocket(hostname,port)torequesta
connectiontotheserver.
4.Theserverlistensforconnectingrequestsfromclientsbyinvoking
serverSocket.accept(),whichblockstheprogramfromexecutingthe
nextstatementuntilaconnectionisestablished.
5.YouneedtousegetInputStream()tocreateastreamtoreceivedatafrom
thesocketandusegetOutputStream()tocreateastreamtosenddatafrom
thesocket.
6.TofindtheIPaddressofaclientthatconnectstoaserver,usegetInetAddress()
fromthesocket.ThenusethegetHostName()andgetHostAddress()toobtainthe
hostnameandIPaddressfromanInetAddressinstance.
7.UsetheThreadclassandcreatemultiplethreadstohandlemultipleconnections,
onethreadperclient.
8.No.Anappletcanonlyconnecttotheserverfromthemachinewheretheappletis
loaded.
9.