资源描述:
《Java语言程序设计与数据结构 基础篇原书第11版PPT及其他教辅资源33slide.ppt》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1Chapter33Networking2ObjectivesToexplainterms:TCP,IP,domainname,domainnameserver,stream-basedcommunications,andpacket-basedcommunications(§33.2).Tocreateserversusingserversockets(§33.2.1)andclientsusingclientsockets(§33.2.2).ToimplementJavanetworkingprogramsusingstreamsockets(§33.2.3).Tode
2、velopanexampleofaclient/serverapplication(§33.2.4).ToobtainInternetaddressesusingtheInetAddressclass(§33.3).Todevelopserversformultipleclients(§33.4).Tosendandreceiveobjectsonanetwork(§33.5).Todevelopaninteractivetic-tac-toegameplayedontheInternet(§33.6).3Client/ServerCommunicationsTheserv
3、ermustberunningwhenaclientstarts.Theserverwaitsforaconnectionrequestfromaclient.Toestablishaserver,youneedtocreateaserversocketandattachittoaport,whichiswheretheserverlistensforconnections.Afteraserversocketiscreated,theservercanusethisstatementtolistenforconnections.Theclientissuesthissta
4、tementtorequestaconnectiontoaserver.Aftertheserveracceptstheconnection,communicationbetweenserverandclientisconductedthesameasforI/Ostreams.4DataTransmissionthroughSocketsInputStreaminput=socket.getInputStream();OutputStreamoutput=socket.getOutputStream();5AClient/ServerExampleProblem:Writ
5、eaclienttosenddatatoaserver.Theserverreceivesthedata,usesittoproducearesult,andthensendstheresultbacktotheclient.Theclientdisplaystheresultontheconsole.Inthisexample,thedatasentfromtheclientistheradiusofacircle,andtheresultproducedbytheserveristheareaofthecircle.6AClient/ServerExample,con
6、t.7AClient/ServerExample,cont.Note:Starttheserver,thentheclient.StartServerStartClientServerClient8TheInetAddressClassOccasionally,youwouldliketoknowwhoisconnectingtotheserver.YoucanusetheInetAddressclasstofindtheclient'shostnameandIPaddress.TheInetAddressclassmodelsanIPaddress.Youcanuseth
7、estatementshownbelowtocreateaninstanceofInetAddressfortheclientonasocket.InetAddressinetAddress=socket.getInetAddress();Next,youcandisplaytheclient'shostnameandIPaddress,asfollows:System.out.println("Client'shostnameis"+inetAddress.getHostName());System.out.pr