资源描述:
《Java语言程序设计10E LiangPPT习题案例31slide.ppt》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1Chapter31Networking2ObjectivesToexplainterms:TCP,IP,domainname,domainnameserver,stream-basedcommunications,andpacket-basedcommunications(§31.2).Tocreateserversusingserversockets(§31.2.1)andclientsusingclientsockets(§31.2.2).ToimplementJavanetworkingprogramsusingstreamsockets(§31.2.
2、3).Todevelopanexampleofaclient/serverapplication(§31.2.4).ToobtainInternetaddressesusingtheInetAddressclass(§31.3).Todevelopserversformultipleclients(§31.4).Tosendandreceiveobjectsonanetwork(§31.5).Todevelopaninteractivetic-tac-toegameplayedontheInternet(§31.6).3Client/ServerCommuni
3、cationsTheservermustberunningwhenaclientstarts.Theserverwaitsforaconnectionrequestfromaclient.Toestablishaserver,youneedtocreateaserversocketandattachittoaport,whichiswheretheserverlistensforconnections.Afteraserversocketiscreated,theservercanusethisstatementtolistenforconnections.T
4、heclientissuesthisstatementtorequestaconnectiontoaserver.Aftertheserveracceptstheconnection,communicationbetweenserverandclientisconductedthesameasforI/Ostreams.4DataTransmissionthroughSocketsInputStreaminput=socket.getInputStream();OutputStreamoutput=socket.getOutputStream();5AClie
5、nt/ServerExampleProblem:Writeaclienttosenddatatoaserver.Theserverreceivesthedata,usesittoproducearesult,andthensendstheresultbacktotheclient.Theclientdisplaystheresultontheconsole.Inthisexample,thedatasentfromtheclientistheradiusofacircle,andtheresultproducedbytheserveristheareaoft
6、hecircle.6AClient/ServerExample,cont.7AClient/ServerExample,cont.ServerCodeClientCodeNote:Starttheserver,thentheclient.StartServerStartClient8TheInetAddressClassOccasionally,youwouldliketoknowwhoisconnectingtotheserver.YoucanusetheInetAddressclasstofindtheclient'shostnameandIPaddres
7、s.TheInetAddressclassmodelsanIPaddress.YoucanusethestatementshownbelowtocreateaninstanceofInetAddressfortheclientonasocket.InetAddressinetAddress=socket.getInetAddress();Next,youcandisplaytheclient'shostnameandIPaddress,asfollows:System.out.println("Client'shostnameis"+inetAddress.g
8、etHostName());Syste