爱问 爱问共享资料 爱问分类
首页 > > > socket开发指南.pdf

socket开发指南.pdf

socket开发指南.pdf

上传者: 413219252
637次下载 0人收藏 暂无简介 简介 2011-08-01 举报

简介:socket开发指南(java

Javasockets101PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksTableofContentsIfyou'reviewingthisdocumentonline,youcanclickanyofthetopicsbelowtolinkdirectlytothatsection.1.Tutorialtips22.Socketbasics33.Anundercoversocket84.Asimpleexample115.Amultithreadedexample186.Apooledexample217.Socketsinreallife278.Summary319.Appendix32Javasockets101Page1Section1.TutorialtipsShouldItakethistutorial?Sockets,whichprovideamechanismforcommunicationbetweentwocomputers,havebeenaroundsincelongbeforetheJavalanguagewasaglimmerinJamesGosling'seye.Thelanguagesimplyletsyouusesocketseffectivelywithouthavingtoknowthedetailsoftheunderlyingoperatingsystem.MostbooksthatfocusonJavacodingeitherfailtocoverthetopic,orleavealottotheimagination.ThistutorialwilltellyouwhatyoureallyneedtoknowtostartusingsocketseffectivelyinyourJavacode.Specifically,we'llcover:*Whatsocketsare*Wheretheyfitintothestructureofprogramsyou'relikelytowrite*Thesimplestsocketsimplementationthatcouldpossiblywork--tohelpyouunderstandthebasics*Adetailedwalkthroughoftwoadditionalexamplesthatexploresocketsinmultithreadedandpooledenvironments*AbriefdiscussionofanapplicationforsocketsintherealworldIfyoucandescribehowtousetheclassesinthejava.netpackage,thistutorialisprobablyalittlebasicforyou,althoughitmightbeagoodrefresher.IfyouhavebeenworkingwithsocketsonPCsandotherplatformsforyears,theinitialsectionsmightboreyou.Butifyouarenewtosockets,andsimplywanttoknowwhattheyareandhowtousethemeffectivelyinyourJavacode,thistutorialisagreatplacetostart.GettinghelpForquestionsaboutthecontentofthistutorial,contacttheauthors,RoyMiller(atrmiller@rolemodelsoft.com)orAdamWilliams(atawilliams@rolemodelsoft.com).RoyMillerandAdamWilliamsareSoftwareDevelopersatRoleModelSoftware,Inc.Theyhaveworkedjointlytoprototypeasocket-basedapplicationfortheTINIJavaplatformfromDallasSemiconductor.RoyandAdamarecurrentlyworkingonportingaCOBOLfinancialtransactionsystemtotheJavaplatform,usingsockets.PriortojoiningRoleModel,RoyspentsixyearswithAndersenConsulting(nowAccenture)developingsoftwareandmanagingprojects.Heco-authoredExtremeProgrammingApplied:PlayingtoWin(Addison-WesleyXPSeries)scheduledforpublicationinOctober2001.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page2Section2.SocketbasicsIntroductionMostprogrammers,whetherthey'recodingintheJavalanguageornot,don'twanttoknowmuchaboutlow-leveldetailsofhowapplicationsondifferentcomputerscommunicatewitheachother.Programmerswanttodealwithhigher-levelabstractionsthatareeasiertounderstand.Javaprogrammerswantobjectsthattheycaninteractwithviaanintuitiveinterface,usingtheJavaconstructswithwhichtheyarefamiliar.Socketsliveinbothworlds--thelow-leveldetailsthatwe'dratheravoidandtheabstractlayerwe'dratherdealwith.Thissectionwillexplorejustenoughofthelow-leveldetailstomaketheabstractapplicationunderstandable.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page3Computernetworking101Computersoperateandcommunicatewithoneanotherinaverysimpleway.Computerchipsareacollectionofon-offswitchesthatstoreandtransmitdataintheformof1sand0s.Whencomputerswanttosharedata,alltheyneedtodoisstreamafewmillionofthesebitsandbytesbackandforth,whileagreeingonspeed,sequence,timing,andsuch.Howwouldyouliketoworryaboutthosedetailseverytimeyouwantedtocommunicateinformationbetweentwoapplications?Toavoidthat,weneedasetofpackagedprotocolsthatcandothejobthesamewayeverytime.Thatwouldallowustohandleourapplication-levelworkwithouthavingtoworryaboutthelow-levelnetworkingdetails.Thesesetsofpackagedprotocolsarecalledstacks.ThemostcommonstackthesedaysisTCP/IP.Moststacks(includingTCP/IP)adhereroughlytotheInternationalStandardsOrganization(ISO)OpenSystemsInterconnectReferenceModel(OSIRM).TheOSIRMsaysthattherearesevenlogicallayersinareliableframeworkforcomputernetworking(seethediagram).Companiesalloverhavecontributedsomethingthatimplementssomeofthelayersinthismodel,fromgeneratingtheelectricalsignals(pulsesoflight,radiofrequency,andsoon)topresentingthedatatoapplications.TCP/IPmapstotwolayersintheOSImodel,asshowninthediagram.Wewon'tgointothedetailsofthelayerstoomuch,butwewantyoutobeawareofwheresocketsfit.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page4WheresocketsfitSocketsresideroughlyattheSessionLayeroftheOSImodel(seethediagram).TheSessionLayerissandwichedbetweentheapplication-orientedupperlayersandthereal-timedatacommunicationlowerlayers.TheSessionLayerprovidesservicesformanagingandcontrollingdataflowbetweentwocomputers.Aspartofthislayer,socketsprovideanabstractionthathidesthecomplexitiesofgettingthebitsandbytesonthewirefortransmission.Inotherwords,socketsallowustotransmitdatabyhavingourapplicationindicatethatitwantstosendsomebytes.Socketsmaskthenutsandboltsofgettingthejobdone.Whenyoupickupyourtelephone,youprovidesoundwavestoasensorthatconvertsyourvoiceintoelectricallytransmittabledata.Thephoneisahuman'sinterfacetothetelecommunicationsnetwork.Youaren'trequiredtoknowthedetailsofhowyourvoiceistransported,onlythepartytowhomyouwouldliketoconnect.Inthesamesense,asocketactsasahigh-levelinterfacethathidesthecomplexitiesoftransmitting1sand0sacrossunknownchannels.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page5ExposingsocketstoanapplicationWhenyouwritecodethatusessockets,thatcodedoesworkatthePresentationLayer.ThePresentationLayerprovidesacommonrepresentationofinformationthattheApplicationLayercanuse.SayyouareplanningtoconnectyourapplicationtoalegacybankingsystemthatunderstandsonlyEBCDIC.YourapplicationdomainobjectsstoreinformationinASCIIformat.Inthiscase,youareresponsibleforwritingcodeatthePresentationLayertoconvertdatafromEBCDICtoASCII,andthen(forexample)toprovideadomainobjecttoyourApplicationLayer.YourApplicationLayercanthendowhateveritwantswiththedomainobject.Thesocket-handlingcodeyouwritelivesonlyatthePresentationLayer.YourApplicationLayerdoesn'thavetoknowanythingabouthowsocketswork.Whataresockets?Nowthatweknowtherolesocketsplay,thequestionremains:Whatisasocket?BruceEckeldescribesasocketthiswayinhisbookThinkinginJava:Thesocketisthesoftwareabstractionusedtorepresentthe"terminals"ofaconnectionbetweentwomachines.Foragivenconnection,there'sasocketoneachmachine,andyoucanimagineahypothetical"cable"runningbetweenthetwomachineswitheachendofthe"cable"pluggedintoasocket.Ofcourse,thephysicalhardwareandcablingbetweenmachinesiscompletelyunknown.Thewholepointoftheabstractionisthatwedon'thavetoknowmorethanisnecessary.Inanutshell,asocketononecomputerthattalkstoasocketonanothercomputercreatesacommunicationchannel.Aprogrammercanusethatchanneltosenddatabetweenthetwomachines.Whenyousenddata,eachlayeroftheTCP/IPstackaddsappropriateheaderinformationtowrapyourdata.Theseheadershelpthestackgetyourdatatoitsdestination.ThegoodnewsisthattheJavalanguagehidesallofthisfromyoubyprovidingthedatatoyourcodeonstreams,whichiswhytheyaresometimescalledstreamingsockets.Thinkofsocketsashandsetsoneithersideofatelephonecall--youandItalkandlistenonourhandsetsonadedicatedchannel.Theconversationdoesn'tenduntilwedecidetohangup(unlesswe'reusingcellphones).Anduntilwehangup,ourrespectivephonelinesarebusy.Ifyouneedtocommunicatebetweentwocomputerswithouttheoverheadofhigher-levelmechanismslikeORBs(andCORBA,RMI,IIOP,andsoon),socketsareforyou.Thelow-leveldetailsofsocketsgetratherinvolved.Fortunately,theJavaplatformgivesyouPresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page6somesimpleyetpowerfulhigher-levelabstractionsthatmakecreatingandusingsocketseasy.TypesofsocketsGenerallyspeaking,socketscomeintwoflavorsintheJavalanguage:*TCPsockets(implementedbytheSocketclass,whichwe'lldiscusslater)*UDPsockets(implementedbytheDatagramSocketclass)TCPandUDPplaythesamerole,buttheydoitdifferently.BothreceivetransportprotocolpacketsandpassalongtheircontentstothePresentationLayer.TCPdividesmessagesintopackets(datagrams)andreassemblestheminthecorrectsequenceatthereceivingend.Italsohandlesrequestingretransmissionofmissingpackets.WithTCP,theupper-levellayershavemuchlesstoworryabout.UDPdoesn'tprovidetheseassemblyandretransmissionrequestingfeatures.Itsimplypassespacketsalong.Theupperlayershavetomakesurethatthemessageiscompleteandassembledincorrectsequence.Ingeneral,UDPimposeslowerperformanceoverheadonyourapplication,butonlyifyourapplicationdoesn'texchangelotsofdataallatonceanddoesn'thavetoreassemblelotsofdatagramstocompleteamessage.Otherwise,TCPisthesimplestandprobablymostefficientchoice.BecausemostreadersaremorelikelytouseTCPthanUDP,we'lllimitourdiscussiontotheTCP-orientedclassesintheJavalanguage.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page7Section3.AnundercoversocketIntroductionTheJavaplatformprovidesimplementationsofsocketsinthejava.netpackage.Inthistutorial,we'llbeworkingwiththefollowingthreeclassesinjava.net:*URLConnection*Socket*ServerSocketTherearemoreclassesinjava.net,butthesearetheonesyou'llrunacrossthemostoften.Let'sbeginwithURLConnection.ThisclassprovidesawaytousesocketsinyourJavacodewithouthavingtoknowanyoftheunderlyingsocketdetails.UsingsocketswithouteventryingTheURLConnectionclassistheabstractsuperclassofallclassesthatcreateacommunicationslinkbetweenanapplicationandaURL.URLConnectionsaremostusefulforgettingdocumentsonWebservers,butcanbeusedtoconnecttoanyresourceidentifiedbyaURL.Instancesofthisclasscanbeusedbothtoreadfromandtowritetotheresource.Forexample,youcouldconnecttoaservletandsendawell-formedXMLStringtotheserverforprocessing.ConcretesubclassesofURLConnection(suchasHttpURLConnection)provideextrafeaturesspecifictotheirimplementation.Forourexample,we'renotdoinganythingspecial,sowe'llmakeuseofthedefaultbehaviorsprovidedbyURLConnectionitself.ConnectingtoaURLinvolvesseveralsteps:*CreatetheURLConnection*Configureitusingvarioussettermethods*ConnecttotheURL*InteractwithitusingvariousgettermethodsNext,we'lllookatsomesamplecodethatdemonstrateshowtouseaURLConnectiontorequestadocumentfromaserver.TheURLClientclassWe'llbeginwiththestructurefortheURLClientclass.importjava.io.*;importjava.net.*;publicclassURLClient{protectedURLConnectionconnection;publicstaticvoidmain(String[]args){}publicStringgetDocumentAt(StringurlString){}}PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page8Thefirstorderofbusinessistoimportjava.netandjava.io.WegiveourclassoneinstancevariabletoholdaURLConnection.Ourclasshasamain()methodthathandlesthelogicflowofsurfingforadocument.OurclassalsohasagetDocumentAt()methodthatconnectstotheserverandasksitforthegivendocument.Wewillgointothedetailsofeachofthesemethodsnext.SurfingforadocumentThemain()methodhandlesthelogicflowofsurfingforadocument:publicstaticvoidmain(String[]args){URLClientclient=newURLClient();Stringyahoo=client.getDocumentAt("http://www.yahoo.com");System.out.println(yahoo);}Ourmain()methodsimplycreatesanewURLClientandcallsgetDocumentAt()withavalidURLString.Whenthatcallreturnsthedocument,westoreitinaStringandthenprintitouttotheconsole.Therealwork,though,getsdoneinthegetDocumentAt()method.RequestingadocumentfromaserverThegetDocumentAt()methodhandlestherealworkofgettingadocumentovertheWeb:publicStringgetDocumentAt(StringurlString){StringBufferdocument=newStringBuffer();try{URLurl=newURL(urlString);URLConnectionconn=url.openConnection();BufferedReaderreader=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringline=null;while((line=reader.readLine())!=null)document.append(line+"\n");reader.close();}catch(MalformedURLExceptione){System.out.println("UnabletoconnecttoURL:"+urlString);}catch(IOExceptione){System.out.println("IOExceptionwhenconnectingtoURL:"+urlString);}returndocument.toString();}ThegetDocumentAt()methodtakesaStringcontainingtheURLofthedocumentwewanttoget.WestartbycreatingaStringBuffertoholdthelinesofthedocument.Next,wecreateanewURLwiththeurlStringwepassedin.ThenwecreateaURLConnectionandopenit:URLConnectionconn=url.openConnection();PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page9OncewehaveaURLConnection,wegetitsInputStreamandwrapitinanInputStreamReader,whichwethenwrapinaBufferedReadersothatwecanreadlinesofthedocumentwe'regettingfromtheserver.We'llusethiswrappingtechniqueoftenwhendealingwithsocketsinJavacode,butwewon'talwaysdiscussitindetail.Youshouldbefamiliarwithitbeforewemoveon:BufferedReaderreader=newBufferedReader(newInputStreamReader(conn.getInputStream()));HavingourBufferedReadermakesreadingthecontentsofourdocumenteasy.WecallreadLine()onreaderinawhileloop:Stringline=null;while((line=reader.readLine())!=null)document.append(line+"\n");ThecalltoreadLine()isgoingtoblockuntilinreachesalineterminationcharacter(forexample,anewlinecharacter)intheincomingbytesontheInputStream.Ifitdoesn'tgetone,itwillkeepwaiting.Itwillreturnnullonlywhentheconnectionisclosed.Inthiscase,oncewegetaline,weappendittotheStringBuffercalleddocument,alongwithanewlinecharacter.Thispreservestheformatofthedocumentthatwasreadontheserverside.Whenwe'redonereadinglines,weclosetheBufferedReader:reader.close();IftheurlStringsuppliedtoaURLconstructorisinvalid,aMalformedURLExceptionisthrown.Ifsomethingelsegoeswrong,suchaswhengettingtheInputStreamontheconnection,anIOExceptionisthrown.WrappingupBeneaththecovers,URLConnectionusesasockettoreadfromtheURLwespecified(whichjustresolvestoanIPaddress),butwedon'thavetoknowaboutitandwedon'tcare.Butthere'smoretothestory;we'llgettothatshortly.Beforewemoveon,let'sreviewthestepstocreateanduseaURLConnection:1.InstantiateaURLwithavalidURLStringoftheresourceyou'reconnectingto(throwsaMalformedURLExceptionifthere'saproblem).2.OpenaconnectiononthatURL.3.WraptheInputStreamforthatconnectioninaBufferedReadersoyoucanreadlines.4.ReadthedocumentusingyourBufferedReader.5.CloseyourBufferedReader.YoucanfindthecompletecodelistingforURLClientatCodelistingforURLClientonpage32.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page10Section4.AsimpleexampleBackgroundTheexamplewe'llcoverinthissectionillustrateshowyoucanuseSocketandServerSocketinyourJavacode.TheclientusesaSockettoconnecttoaserver.Theserverlistensonport3000withaServerSocket.Theclientrequeststhecontentsofafileontheserver'sC:drive.Forthesakeofclarity,wesplittheexampleintotheclientsideandtheserverside.Attheend,we'llputitalltogethersoyoucanseetheentirepicture.WedevelopedthiscodeinIBMVisualAgeforJava3.5,whichusesJDK1.2.Tocreatethisexampleforyourself,JDK1.1.7orgreatershouldbefine.Theclientandtheserverwillrunonasinglemachine,sodon'tworryabouthavinganetworkavailable.CreatingtheRemoteFileClientclassHereisthestructurefortheRemoteFileClientclass:importjava.io.*;importjava.net.*;publicclassRemoteFileClient{protectedStringhostIp;protectedinthostPort;protectedBufferedReadersocketReader;protectedPrintWritersocketWriter;publicRemoteFileClient(StringaHostIp,intaHostPort){hostIp=aHostIp;hostPort=aHostPort;}publicstaticvoidmain(String[]args){}publicvoidsetUpConnection(){}publicStringgetFile(StringfileNameToGet){}publicvoidtearDownConnection(){}}Firstweimportjava.netandjava.io.Thejava.netpackagegivesyouthesockettoolsyouneed.Thejava.iopackagegivesyoutoolstoreadandwritestreams,whichistheonlywayyoucancommunicatewithTCPsockets.Wegiveourclassinstancevariablestosupportreadingfromandwritingtosocketstreams,andtostoredetailsoftheremotehosttowhichwewillconnect.TheconstructorforourclasstakesanIPaddressandaportnumberforaremotehostandassignsthemtoinstancevariables.Ourclasshasamain()methodandthreeothermethods.We'llgointothedetailsofthesemethodslater.Fornow,justknowthatsetUpConnection()willconnecttotheremoteserver,getFile()willasktheremoteserverforthecontentsoffileNameToGet,andPresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page11tearDownConnection()willdisconnectfromtheremoteserver.Implementingmain()Hereweimplementthemain()method,whichwillcreatetheRemoteFileClient,useittogetthecontentsofaremotefile,andthenprinttheresult:publicstaticvoidmain(String[]args){RemoteFileClientremoteFileClient=newRemoteFileClient("127.0.0.1",3000);remoteFileClient.setUpConnection();StringfileContents=remoteFileClient.getFile("C:\\WINNT\\Temp\\RemoteFile.txt");remoteFileClient.tearDownConnection();System.out.println(fileContents);}Themain()methodinstantiatesanewRemoteFileClient(theclient)withanIPaddressandportnumberforthehost.Then,wetelltheclienttosetupaconnectiontothehost(moreonthislater).Next,wetelltheclienttogetthecontentsofaspecifiedfileonthehost.Finally,wetelltheclienttoteardownitsconnectiontothehost.Weprintoutthecontentsofthefiletotheconsole,justtoproveeverythingworkedasplanned.SettingupaconnectionHereweimplementthesetUpConnection()method,whichwillsetupourSocketandgiveusac

socket开发指南.pdf

socket开发指南.pdf

上传者: 413219252
637次下载 0人收藏 暂无简介 简介 2011-08-01 举报

简介:socket开发指南(java

Javasockets101PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksTableofContentsIfyou'reviewingthisdocumentonline,youcanclickanyofthetopicsbelowtolinkdirectlytothatsection.1.Tutorialtips22.Socketbasics33.Anundercoversocket84.Asimpleexample115.Amultithreadedexample186.Apooledexample217.Socketsinreallife278.Summary319.Appendix32Javasockets101Page1Section1.TutorialtipsShouldItakethistutorial?Sockets,whichprovideamechanismforcommunicationbetweentwocomputers,havebeenaroundsincelongbeforetheJavalanguagewasaglimmerinJamesGosling'seye.Thelanguagesimplyletsyouusesocketseffectivelywithouthavingtoknowthedetailsoftheunderlyingoperatingsystem.MostbooksthatfocusonJavacodingeitherfailtocoverthetopic,orleavealottotheimagination.ThistutorialwilltellyouwhatyoureallyneedtoknowtostartusingsocketseffectivelyinyourJavacode.Specifically,we'llcover:*Whatsocketsare*Wheretheyfitintothestructureofprogramsyou'relikelytowrite*Thesimplestsocketsimplementationthatcouldpossiblywork--tohelpyouunderstandthebasics*Adetailedwalkthroughoftwoadditionalexamplesthatexploresocketsinmultithreadedandpooledenvironments*AbriefdiscussionofanapplicationforsocketsintherealworldIfyoucandescribehowtousetheclassesinthejava.netpackage,thistutorialisprobablyalittlebasicforyou,althoughitmightbeagoodrefresher.IfyouhavebeenworkingwithsocketsonPCsandotherplatformsforyears,theinitialsectionsmightboreyou.Butifyouarenewtosockets,andsimplywanttoknowwhattheyareandhowtousethemeffectivelyinyourJavacode,thistutorialisagreatplacetostart.GettinghelpForquestionsaboutthecontentofthistutorial,contacttheauthors,RoyMiller(atrmiller@rolemodelsoft.com)orAdamWilliams(atawilliams@rolemodelsoft.com).RoyMillerandAdamWilliamsareSoftwareDevelopersatRoleModelSoftware,Inc.Theyhaveworkedjointlytoprototypeasocket-basedapplicationfortheTINIJavaplatformfromDallasSemiconductor.RoyandAdamarecurrentlyworkingonportingaCOBOLfinancialtransactionsystemtotheJavaplatform,usingsockets.PriortojoiningRoleModel,RoyspentsixyearswithAndersenConsulting(nowAccenture)developingsoftwareandmanagingprojects.Heco-authoredExtremeProgrammingApplied:PlayingtoWin(Addison-WesleyXPSeries)scheduledforpublicationinOctober2001.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page2Section2.SocketbasicsIntroductionMostprogrammers,whetherthey'recodingintheJavalanguageornot,don'twanttoknowmuchaboutlow-leveldetailsofhowapplicationsondifferentcomputerscommunicatewitheachother.Programmerswanttodealwithhigher-levelabstractionsthatareeasiertounderstand.Javaprogrammerswantobjectsthattheycaninteractwithviaanintuitiveinterface,usingtheJavaconstructswithwhichtheyarefamiliar.Socketsliveinbothworlds--thelow-leveldetailsthatwe'dratheravoidandtheabstractlayerwe'dratherdealwith.Thissectionwillexplorejustenoughofthelow-leveldetailstomaketheabstractapplicationunderstandable.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page3Computernetworking101Computersoperateandcommunicatewithoneanotherinaverysimpleway.Computerchipsareacollectionofon-offswitchesthatstoreandtransmitdataintheformof1sand0s.Whencomputerswanttosharedata,alltheyneedtodoisstreamafewmillionofthesebitsandbytesbackandforth,whileagreeingonspeed,sequence,timing,andsuch.Howwouldyouliketoworryaboutthosedetailseverytimeyouwantedtocommunicateinformationbetweentwoapplications?Toavoidthat,weneedasetofpackagedprotocolsthatcandothejobthesamewayeverytime.Thatwouldallowustohandleourapplication-levelworkwithouthavingtoworryaboutthelow-levelnetworkingdetails.Thesesetsofpackagedprotocolsarecalledstacks.ThemostcommonstackthesedaysisTCP/IP.Moststacks(includingTCP/IP)adhereroughlytotheInternationalStandardsOrganization(ISO)OpenSystemsInterconnectReferenceModel(OSIRM).TheOSIRMsaysthattherearesevenlogicallayersinareliableframeworkforcomputernetworking(seethediagram).Companiesalloverhavecontributedsomethingthatimplementssomeofthelayersinthismodel,fromgeneratingtheelectricalsignals(pulsesoflight,radiofrequency,andsoon)topresentingthedatatoapplications.TCP/IPmapstotwolayersintheOSImodel,asshowninthediagram.Wewon'tgointothedetailsofthelayerstoomuch,butwewantyoutobeawareofwheresocketsfit.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page4WheresocketsfitSocketsresideroughlyattheSessionLayeroftheOSImodel(seethediagram).TheSessionLayerissandwichedbetweentheapplication-orientedupperlayersandthereal-timedatacommunicationlowerlayers.TheSessionLayerprovidesservicesformanagingandcontrollingdataflowbetweentwocomputers.Aspartofthislayer,socketsprovideanabstractionthathidesthecomplexitiesofgettingthebitsandbytesonthewirefortransmission.Inotherwords,socketsallowustotransmitdatabyhavingourapplicationindicatethatitwantstosendsomebytes.Socketsmaskthenutsandboltsofgettingthejobdone.Whenyoupickupyourtelephone,youprovidesoundwavestoasensorthatconvertsyourvoiceintoelectricallytransmittabledata.Thephoneisahuman'sinterfacetothetelecommunicationsnetwork.Youaren'trequiredtoknowthedetailsofhowyourvoiceistransported,onlythepartytowhomyouwouldliketoconnect.Inthesamesense,asocketactsasahigh-levelinterfacethathidesthecomplexitiesoftransmitting1sand0sacrossunknownchannels.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page5ExposingsocketstoanapplicationWhenyouwritecodethatusessockets,thatcodedoesworkatthePresentationLayer.ThePresentationLayerprovidesacommonrepresentationofinformationthattheApplicationLayercanuse.SayyouareplanningtoconnectyourapplicationtoalegacybankingsystemthatunderstandsonlyEBCDIC.YourapplicationdomainobjectsstoreinformationinASCIIformat.Inthiscase,youareresponsibleforwritingcodeatthePresentationLayertoconvertdatafromEBCDICtoASCII,andthen(forexample)toprovideadomainobjecttoyourApplicationLayer.YourApplicationLayercanthendowhateveritwantswiththedomainobject.Thesocket-handlingcodeyouwritelivesonlyatthePresentationLayer.YourApplicationLayerdoesn'thavetoknowanythingabouthowsocketswork.Whataresockets?Nowthatweknowtherolesocketsplay,thequestionremains:Whatisasocket?BruceEckeldescribesasocketthiswayinhisbookThinkinginJava:Thesocketisthesoftwareabstractionusedtorepresentthe"terminals"ofaconnectionbetweentwomachines.Foragivenconnection,there'sasocketoneachmachine,andyoucanimagineahypothetical"cable"runningbetweenthetwomachineswitheachendofthe"cable"pluggedintoasocket.Ofcourse,thephysicalhardwareandcablingbetweenmachinesiscompletelyunknown.Thewholepointoftheabstractionisthatwedon'thavetoknowmorethanisnecessary.Inanutshell,asocketononecomputerthattalkstoasocketonanothercomputercreatesacommunicationchannel.Aprogrammercanusethatchanneltosenddatabetweenthetwomachines.Whenyousenddata,eachlayeroftheTCP/IPstackaddsappropriateheaderinformationtowrapyourdata.Theseheadershelpthestackgetyourdatatoitsdestination.ThegoodnewsisthattheJavalanguagehidesallofthisfromyoubyprovidingthedatatoyourcodeonstreams,whichiswhytheyaresometimescalledstreamingsockets.Thinkofsocketsashandsetsoneithersideofatelephonecall--youandItalkandlistenonourhandsetsonadedicatedchannel.Theconversationdoesn'tenduntilwedecidetohangup(unlesswe'reusingcellphones).Anduntilwehangup,ourrespectivephonelinesarebusy.Ifyouneedtocommunicatebetweentwocomputerswithouttheoverheadofhigher-levelmechanismslikeORBs(andCORBA,RMI,IIOP,andsoon),socketsareforyou.Thelow-leveldetailsofsocketsgetratherinvolved.Fortunately,theJavaplatformgivesyouPresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page6somesimpleyetpowerfulhigher-levelabstractionsthatmakecreatingandusingsocketseasy.TypesofsocketsGenerallyspeaking,socketscomeintwoflavorsintheJavalanguage:*TCPsockets(implementedbytheSocketclass,whichwe'lldiscusslater)*UDPsockets(implementedbytheDatagramSocketclass)TCPandUDPplaythesamerole,buttheydoitdifferently.BothreceivetransportprotocolpacketsandpassalongtheircontentstothePresentationLayer.TCPdividesmessagesintopackets(datagrams)andreassemblestheminthecorrectsequenceatthereceivingend.Italsohandlesrequestingretransmissionofmissingpackets.WithTCP,theupper-levellayershavemuchlesstoworryabout.UDPdoesn'tprovidetheseassemblyandretransmissionrequestingfeatures.Itsimplypassespacketsalong.Theupperlayershavetomakesurethatthemessageiscompleteandassembledincorrectsequence.Ingeneral,UDPimposeslowerperformanceoverheadonyourapplication,butonlyifyourapplicationdoesn'texchangelotsofdataallatonceanddoesn'thavetoreassemblelotsofdatagramstocompleteamessage.Otherwise,TCPisthesimplestandprobablymostefficientchoice.BecausemostreadersaremorelikelytouseTCPthanUDP,we'lllimitourdiscussiontotheTCP-orientedclassesintheJavalanguage.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page7Section3.AnundercoversocketIntroductionTheJavaplatformprovidesimplementationsofsocketsinthejava.netpackage.Inthistutorial,we'llbeworkingwiththefollowingthreeclassesinjava.net:*URLConnection*Socket*ServerSocketTherearemoreclassesinjava.net,butthesearetheonesyou'llrunacrossthemostoften.Let'sbeginwithURLConnection.ThisclassprovidesawaytousesocketsinyourJavacodewithouthavingtoknowanyoftheunderlyingsocketdetails.UsingsocketswithouteventryingTheURLConnectionclassistheabstractsuperclassofallclassesthatcreateacommunicationslinkbetweenanapplicationandaURL.URLConnectionsaremostusefulforgettingdocumentsonWebservers,butcanbeusedtoconnecttoanyresourceidentifiedbyaURL.Instancesofthisclasscanbeusedbothtoreadfromandtowritetotheresource.Forexample,youcouldconnecttoaservletandsendawell-formedXMLStringtotheserverforprocessing.ConcretesubclassesofURLConnection(suchasHttpURLConnection)provideextrafeaturesspecifictotheirimplementation.Forourexample,we'renotdoinganythingspecial,sowe'llmakeuseofthedefaultbehaviorsprovidedbyURLConnectionitself.ConnectingtoaURLinvolvesseveralsteps:*CreatetheURLConnection*Configureitusingvarioussettermethods*ConnecttotheURL*InteractwithitusingvariousgettermethodsNext,we'lllookatsomesamplecodethatdemonstrateshowtouseaURLConnectiontorequestadocumentfromaserver.TheURLClientclassWe'llbeginwiththestructurefortheURLClientclass.importjava.io.*;importjava.net.*;publicclassURLClient{protectedURLConnectionconnection;publicstaticvoidmain(String[]args){}publicStringgetDocumentAt(StringurlString){}}PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page8Thefirstorderofbusinessistoimportjava.netandjava.io.WegiveourclassoneinstancevariabletoholdaURLConnection.Ourclasshasamain()methodthathandlesthelogicflowofsurfingforadocument.OurclassalsohasagetDocumentAt()methodthatconnectstotheserverandasksitforthegivendocument.Wewillgointothedetailsofeachofthesemethodsnext.SurfingforadocumentThemain()methodhandlesthelogicflowofsurfingforadocument:publicstaticvoidmain(String[]args){URLClientclient=newURLClient();Stringyahoo=client.getDocumentAt("http://www.yahoo.com");System.out.println(yahoo);}Ourmain()methodsimplycreatesanewURLClientandcallsgetDocumentAt()withavalidURLString.Whenthatcallreturnsthedocument,westoreitinaStringandthenprintitouttotheconsole.Therealwork,though,getsdoneinthegetDocumentAt()method.RequestingadocumentfromaserverThegetDocumentAt()methodhandlestherealworkofgettingadocumentovertheWeb:publicStringgetDocumentAt(StringurlString){StringBufferdocument=newStringBuffer();try{URLurl=newURL(urlString);URLConnectionconn=url.openConnection();BufferedReaderreader=newBufferedReader(newInputStreamReader(conn.getInputStream()));Stringline=null;while((line=reader.readLine())!=null)document.append(line+"\n");reader.close();}catch(MalformedURLExceptione){System.out.println("UnabletoconnecttoURL:"+urlString);}catch(IOExceptione){System.out.println("IOExceptionwhenconnectingtoURL:"+urlString);}returndocument.toString();}ThegetDocumentAt()methodtakesaStringcontainingtheURLofthedocumentwewanttoget.WestartbycreatingaStringBuffertoholdthelinesofthedocument.Next,wecreateanewURLwiththeurlStringwepassedin.ThenwecreateaURLConnectionandopenit:URLConnectionconn=url.openConnection();PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page9OncewehaveaURLConnection,wegetitsInputStreamandwrapitinanInputStreamReader,whichwethenwrapinaBufferedReadersothatwecanreadlinesofthedocumentwe'regettingfromtheserver.We'llusethiswrappingtechniqueoftenwhendealingwithsocketsinJavacode,butwewon'talwaysdiscussitindetail.Youshouldbefamiliarwithitbeforewemoveon:BufferedReaderreader=newBufferedReader(newInputStreamReader(conn.getInputStream()));HavingourBufferedReadermakesreadingthecontentsofourdocumenteasy.WecallreadLine()onreaderinawhileloop:Stringline=null;while((line=reader.readLine())!=null)document.append(line+"\n");ThecalltoreadLine()isgoingtoblockuntilinreachesalineterminationcharacter(forexample,anewlinecharacter)intheincomingbytesontheInputStream.Ifitdoesn'tgetone,itwillkeepwaiting.Itwillreturnnullonlywhentheconnectionisclosed.Inthiscase,oncewegetaline,weappendittotheStringBuffercalleddocument,alongwithanewlinecharacter.Thispreservestheformatofthedocumentthatwasreadontheserverside.Whenwe'redonereadinglines,weclosetheBufferedReader:reader.close();IftheurlStringsuppliedtoaURLconstructorisinvalid,aMalformedURLExceptionisthrown.Ifsomethingelsegoeswrong,suchaswhengettingtheInputStreamontheconnection,anIOExceptionisthrown.WrappingupBeneaththecovers,URLConnectionusesasockettoreadfromtheURLwespecified(whichjustresolvestoanIPaddress),butwedon'thavetoknowaboutitandwedon'tcare.Butthere'smoretothestory;we'llgettothatshortly.Beforewemoveon,let'sreviewthestepstocreateanduseaURLConnection:1.InstantiateaURLwithavalidURLStringoftheresourceyou'reconnectingto(throwsaMalformedURLExceptionifthere'saproblem).2.OpenaconnectiononthatURL.3.WraptheInputStreamforthatconnectioninaBufferedReadersoyoucanreadlines.4.ReadthedocumentusingyourBufferedReader.5.CloseyourBufferedReader.YoucanfindthecompletecodelistingforURLClientatCodelistingforURLClientonpage32.PresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page10Section4.AsimpleexampleBackgroundTheexamplewe'llcoverinthissectionillustrateshowyoucanuseSocketandServerSocketinyourJavacode.TheclientusesaSockettoconnecttoaserver.Theserverlistensonport3000withaServerSocket.Theclientrequeststhecontentsofafileontheserver'sC:drive.Forthesakeofclarity,wesplittheexampleintotheclientsideandtheserverside.Attheend,we'llputitalltogethersoyoucanseetheentirepicture.WedevelopedthiscodeinIBMVisualAgeforJava3.5,whichusesJDK1.2.Tocreatethisexampleforyourself,JDK1.1.7orgreatershouldbefine.Theclientandtheserverwillrunonasinglemachine,sodon'tworryabouthavinganetworkavailable.CreatingtheRemoteFileClientclassHereisthestructurefortheRemoteFileClientclass:importjava.io.*;importjava.net.*;publicclassRemoteFileClient{protectedStringhostIp;protectedinthostPort;protectedBufferedReadersocketReader;protectedPrintWritersocketWriter;publicRemoteFileClient(StringaHostIp,intaHostPort){hostIp=aHostIp;hostPort=aHostPort;}publicstaticvoidmain(String[]args){}publicvoidsetUpConnection(){}publicStringgetFile(StringfileNameToGet){}publicvoidtearDownConnection(){}}Firstweimportjava.netandjava.io.Thejava.netpackagegivesyouthesockettoolsyouneed.Thejava.iopackagegivesyoutoolstoreadandwritestreams,whichistheonlywayyoucancommunicatewithTCPsockets.Wegiveourclassinstancevariablestosupportreadingfromandwritingtosocketstreams,andtostoredetailsoftheremotehosttowhichwewillconnect.TheconstructorforourclasstakesanIPaddressandaportnumberforaremotehostandassignsthemtoinstancevariables.Ourclasshasamain()methodandthreeothermethods.We'llgointothedetailsofthesemethodslater.Fornow,justknowthatsetUpConnection()willconnecttotheremoteserver,getFile()willasktheremoteserverforthecontentsoffileNameToGet,andPresentedbydeveloperWorks,yoursourceforgreattutorialsibm.com/developerWorksJavasockets101Page11tearDownConnection()willdisconnectfromtheremoteserver.Implementingmain()Hereweimplementthemain()method,whichwillcreatetheRemoteFileClient,useittogetthecontentsofaremotefile,andthenprinttheresult:publicstaticvoidmain(String[]args){RemoteFileClientremoteFileClient=newRemoteFileClient("127.0.0.1",3000);remoteFileClient.setUpConnection();StringfileContents=remoteFileClient.getFile("C:\\WINNT\\Temp\\RemoteFile.txt");remoteFileClient.tearDownConnection();System.out.println(fileContents);}Themain()methodinstantiatesanewRemoteFileClient(theclient)withanIPaddressandportnumberforthehost.Then,wetelltheclienttosetupaconnectiontothehost(moreonthislater).Next,wetelltheclienttogetthecontentsofaspecifiedfileonthehost.Finally,wetelltheclienttoteardownitsconnectiontothehost.Weprintoutthecontentsofthefiletotheconsole,justtoproveeverythingworkedasplanned.SettingupaconnectionHereweimplementthesetUpConnection()method,whichwillsetupourSocketandgiveusac
  • 相关资料
  • 该用户的其他资料
  • 名称/格式
  • 下载次数
  • 资料大小
  • 名称/格式
  • 下载次数
  • 资料大小

用户评论

0/200
暂无评论
上传我的资料

资料阅读排行

关闭

请选择举报的类型

关闭

提示

提交成功!

感谢您对爱问共享资料的支持,我们将尽快核实并处理您的举报信息。

关闭

提示

提交失败!

您的举报信息提交失败,请重试!

关闭

提示

重复举报!

亲爱的用户!感觉您对爱问共享资料的支持,请勿重复举报噢!

全屏 缩小 放大
收藏
资料评价:

/ 36
所需积分:0 立即下载
返回
顶部
举报
资料
关闭

温馨提示

感谢您对爱问共享资料的支持,精彩活动将尽快为您呈现,敬请期待!