关闭

关闭

封号提示

内容

首页 socket开发指南.pdf

socket开发指南.pdf

socket开发指南.pdf

上传者: 413219252 2011-08-01 评分 5 0 310 42 1409 暂无简介 简介 举报

简介:本文档为《socket开发指南pdf》,可适用于IT/计算机领域,主题内容包含JavasocketsPresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeve符等。

JavasocketsPresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksTableofContentsIfyou'reviewingthisdocumentonline,youcanclickanyofthetopicsbelowtolinkdirectlytothatsectionTutorialtipsSocketbasicsAnundercoversocketAsimpleexampleAmultithreadedexampleApooledexampleSocketsinreallifeSummaryAppendixJavasocketsPageSectionTutorialtipsShouldItakethistutorialSockets,whichprovideamechanismforcommunicationbetweentwocomputers,havebeenaroundsincelongbeforetheJavalanguagewasaglimmerinJamesGosling'seyeThelanguagesimplyletsyouusesocketseffectivelywithouthavingtoknowthedetailsoftheunderlyingoperatingsystemMostbooksthatfocusonJavacodingeitherfailtocoverthetopic,orleavealottotheimaginationThistutorialwilltellyouwhatyoureallyneedtoknowtostartusingsocketseffectivelyinyourJavacodeSpecifically,we'llcover:*Whatsocketsare*Wheretheyfitintothestructureofprogramsyou'relikelytowrite*Thesimplestsocketsimplementationthatcouldpossiblyworktohelpyouunderstandthebasics*Adetailedwalkthroughoftwoadditionalexamplesthatexploresocketsinmultithreadedandpooledenvironments*AbriefdiscussionofanapplicationforsocketsintherealworldIfyoucandescribehowtousetheclassesinthejavanetpackage,thistutorialisprobablyalittlebasicforyou,althoughitmightbeagoodrefresherIfyouhavebeenworkingwithsocketsonPCsandotherplatformsforyears,theinitialsectionsmightboreyouButifyouarenewtosockets,andsimplywanttoknowwhattheyareandhowtousethemeffectivelyinyourJavacode,thistutorialisagreatplacetostartGettinghelpForquestionsaboutthecontentofthistutorial,contacttheauthors,RoyMiller(atrmillerrolemodelsoftcom)orAdamWilliams(atawilliamsrolemodelsoftcom)RoyMillerandAdamWilliamsareSoftwareDevelopersatRoleModelSoftware,IncTheyhaveworkedjointlytoprototypeasocketbasedapplicationfortheTINIJavaplatformfromDallasSemiconductorRoyandAdamarecurrentlyworkingonportingaCOBOLfinancialtransactionsystemtotheJavaplatform,usingsocketsPriortojoiningRoleModel,RoyspentsixyearswithAndersenConsulting(nowAccenture)developingsoftwareandmanagingprojectsHecoauthoredExtremeProgrammingApplied:PlayingtoWin(AddisonWesleyXPSeries)scheduledforpublicationinOctoberPresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPageSectionSocketbasicsIntroductionMostprogrammers,whetherthey'recodingintheJavalanguageornot,don'twanttoknowmuchaboutlowleveldetailsofhowapplicationsondifferentcomputerscommunicatewitheachotherProgrammerswanttodealwithhigherlevelabstractionsthatareeasiertounderstandJavaprogrammerswantobjectsthattheycaninteractwithviaanintuitiveinterface,usingtheJavaconstructswithwhichtheyarefamiliarSocketsliveinbothworldsthelowleveldetailsthatwe'dratheravoidandtheabstractlayerwe'dratherdealwithThissectionwillexplorejustenoughofthelowleveldetailstomaketheabstractapplicationunderstandablePresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPageComputernetworkingComputersoperateandcommunicatewithoneanotherinaverysimplewayComputerchipsareacollectionofonoffswitchesthatstoreandtransmitdataintheformofsandsWhencomputerswanttosharedata,alltheyneedtodoisstreamafewmillionofthesebitsandbytesbackandforth,whileagreeingonspeed,sequence,timing,andsuchHowwouldyouliketoworryaboutthosedetailseverytimeyouwantedtocommunicateinformationbetweentwoapplicationsToavoidthat,weneedasetofpackagedprotocolsthatcandothejobthesamewayeverytimeThatwouldallowustohandleourapplicationlevelworkwithouthavingtoworryaboutthelowlevelnetworkingdetailsThesesetsofpackagedprotocolsarecalledstacksThemostcommonstackthesedaysisTCPIPMoststacks(includingTCPIP)adhereroughlytotheInternationalStandardsOrganization(ISO)OpenSystemsInterconnectReferenceModel(OSIRM)TheOSIRMsaysthattherearesevenlogicallayersinareliableframeworkforcomputernetworking(seethediagram)Companiesalloverhavecontributedsomethingthatimplementssomeofthelayersinthismodel,fromgeneratingtheelectricalsignals(pulsesoflight,radiofrequency,andsoon)topresentingthedatatoapplicationsTCPIPmapstotwolayersintheOSImodel,asshowninthediagramWewon'tgointothedetailsofthelayerstoomuch,butwewantyoutobeawareofwheresocketsfitPresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPageWheresocketsfitSocketsresideroughlyattheSessionLayeroftheOSImodel(seethediagram)TheSessionLayerissandwichedbetweentheapplicationorientedupperlayersandtherealtimedatacommunicationlowerlayersTheSessionLayerprovidesservicesformanagingandcontrollingdataflowbetweentwocomputersAspartofthislayer,socketsprovideanabstractionthathidesthecomplexitiesofgettingthebitsandbytesonthewirefortransmissionInotherwords,socketsallowustotransmitdatabyhavingourapplicationindicatethatitwantstosendsomebytesSocketsmaskthenutsandboltsofgettingthejobdoneWhenyoupickupyourtelephone,youprovidesoundwavestoasensorthatconvertsyourvoiceintoelectricallytransmittabledataThephoneisahuman'sinterfacetothetelecommunicationsnetworkYouaren'trequiredtoknowthedetailsofhowyourvoiceistransported,onlythepartytowhomyouwouldliketoconnectInthesamesense,asocketactsasahighlevelinterfacethathidesthecomplexitiesoftransmittingsandsacrossunknownchannelsPresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPageExposingsocketstoanapplicationWhenyouwritecodethatusessockets,thatcodedoesworkatthePresentationLayerThePresentationLayerprovidesacommonrepresentationofinformationthattheApplicationLayercanuseSayyouareplanningtoconnectyourapplicationtoalegacybankingsystemthatunderstandsonlyEBCDICYourapplicationdomainobjectsstoreinformationinASCIIformatInthiscase,youareresponsibleforwritingcodeatthePresentationLayertoconvertdatafromEBCDICtoASCII,andthen(forexample)toprovideadomainobjecttoyourApplicationLayerYourApplicationLayercanthendowhateveritwantswiththedomainobjectThesockethandlingcodeyouwritelivesonlyatthePresentationLayerYourApplicationLayerdoesn'thavetoknowanythingabouthowsocketsworkWhataresocketsNowthatweknowtherolesocketsplay,thequestionremains:WhatisasocketBruceEckeldescribesasocketthiswayinhisbookThinkinginJava:Thesocketisthesoftwareabstractionusedtorepresentthe"terminals"ofaconnectionbetweentwomachinesForagivenconnection,there'sasocketoneachmachine,andyoucanimagineahypothetical"cable"runningbetweenthetwomachineswitheachendofthe"cable"pluggedintoasocketOfcourse,thephysicalhardwareandcablingbetweenmachinesiscompletelyunknownThewholepointoftheabstractionisthatwedon'thavetoknowmorethanisnecessaryInanutshell,asocketononecomputerthattalkstoasocketonanothercomputercreatesacommunicationchannelAprogrammercanusethatchanneltosenddatabetweenthetwomachinesWhenyousenddata,eachlayeroftheTCPIPstackaddsappropriateheaderinformationtowrapyourdataTheseheadershelpthestackgetyourdatatoitsdestinationThegoodnewsisthattheJavalanguagehidesallofthisfromyoubyprovidingthedatatoyourcodeonstreams,whichiswhytheyaresometimescalledstreamingsocketsThinkofsocketsashandsetsoneithersideofatelephonecallyouandItalkandlistenonourhandsetsonadedicatedchannelTheconversationdoesn'tenduntilwedecidetohangup(unlesswe'reusingcellphones)Anduntilwehangup,ourrespectivephonelinesarebusyIfyouneedtocommunicatebetweentwocomputerswithouttheoverheadofhigherlevelmechanismslikeORBs(andCORBA,RMI,IIOP,andsoon),socketsareforyouThelowleveldetailsofsocketsgetratherinvolvedFortunately,theJavaplatformgivesyouPresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPagesomesimpleyetpowerfulhigherlevelabstractionsthatmakecreatingandusingsocketseasyTypesofsocketsGenerallyspeaking,socketscomeintwoflavorsintheJavalanguage:*TCPsockets(implementedbytheSocketclass,whichwe'lldiscusslater)*UDPsockets(implementedbytheDatagramSocketclass)TCPandUDPplaythesamerole,buttheydoitdifferentlyBothreceivetransportprotocolpacketsandpassalongtheircontentstothePresentationLayerTCPdividesmessagesintopackets(datagrams)andreassemblestheminthecorrectsequenceatthereceivingendItalsohandlesrequestingretransmissionofmissingpacketsWithTCP,theupperlevellayershavemuchlesstoworryaboutUDPdoesn'tprovidetheseassemblyandretransmissionrequestingfeaturesItsimplypassespacketsalongTheupperlayershavetomakesurethatthemessageiscompleteandassembledincorrectsequenceIngeneral,UDPimposeslowerperformanceoverheadonyourapplication,butonlyifyourapplicationdoesn'texchangelotsofdataallatonceanddoesn'thavetoreassemblelotsofdatagramstocompleteamessageOtherwise,TCPisthesimplestandprobablymostefficientchoiceBecausemostreadersaremorelikelytouseTCPthanUDP,we'lllimitourdiscussiontotheTCPorientedclassesintheJavalanguagePresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPageSectionAnundercoversocketIntroductionTheJavaplatformprovidesimplementationsofsocketsinthejavanetpackageInthistutorial,we'llbeworkingwiththefollowingthreeclassesinjavanet:*URLConnection*Socket*ServerSocketTherearemoreclassesinjavanet,butthesearetheonesyou'llrunacrossthemostoftenLet'sbeginwithURLConnectionThisclassprovidesawaytousesocketsinyourJavacodewithouthavingtoknowanyoftheunderlyingsocketdetailsUsingsocketswithouteventryingTheURLConnectionclassistheabstractsuperclassofallclassesthatcreateacommunicationslinkbetweenanapplicationandaURLURLConnectionsaremostusefulforgettingdocumentsonWebservers,butcanbeusedtoconnecttoanyresourceidentifiedbyaURLInstancesofthisclasscanbeusedbothtoreadfromandtowritetotheresourceForexample,youcouldconnecttoaservletandsendawellformedXMLStringtotheserverforprocessingConcretesubclassesofURLConnection(suchasHttpURLConnection)provideextrafeaturesspecifictotheirimplementationForourexample,we'renotdoinganythingspecial,sowe'llmakeuseofthedefaultbehaviorsprovidedbyURLConnectionitselfConnectingtoaURLinvolvesseveralsteps:*CreatetheURLConnection*Configureitusingvarioussettermethods*ConnecttotheURL*InteractwithitusingvariousgettermethodsNext,we'lllookatsomesamplecodethatdemonstrateshowtouseaURLConnectiontorequestadocumentfromaserverTheURLClientclassWe'llbeginwiththestructurefortheURLClientclassimportjavaio*importjavanet*publicclassURLClient{protectedURLConnectionconnectionpublicstaticvoidmain(Stringargs){}publicStringgetDocumentAt(StringurlString){}}PresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPageThefirstorderofbusinessistoimportjavanetandjavaioWegiveourclassoneinstancevariabletoholdaURLConnectionOurclasshasamain()methodthathandlesthelogicflowofsurfingforadocumentOurclassalsohasagetDocumentAt()methodthatconnectstotheserverandasksitforthegivendocumentWewillgointothedetailsofeachofthesemethodsnextSurfingforadocumentThemain()methodhandlesthelogicflowofsurfingforadocument:publicstaticvoidmain(Stringargs){URLClientclient=newURLClient()Stringyahoo=clientgetDocumentAt("http:wwwyahoocom")Systemoutprintln(yahoo)}Ourmain()methodsimplycreatesanewURLClientandcallsgetDocumentAt()withavalidURLStringWhenthatcallreturnsthedocument,westoreitinaStringandthenprintitouttotheconsoleTherealwork,though,getsdoneinthegetDocumentAt()methodRequestingadocumentfromaserverThegetDocumentAt()methodhandlestherealworkofgettingadocumentovertheWeb:publicStringgetDocumentAt(StringurlString){StringBufferdocument=newStringBuffer()try{URLurl=newURL(urlString)URLConnectionconn=urlopenConnection()BufferedReaderreader=newBufferedReader(newInputStreamReader(conngetInputStream()))Stringline=while((line=readerreadLine())!=)documentappend(line"n")readerclose()}catch(MalformedURLExceptione){Systemoutprintln("UnabletoconnecttoURL:"urlString)}catch(IOExceptione){Systemoutprintln("IOExceptionwhenconnectingtoURL:"urlString)}returndocumenttoString()}ThegetDocumentAt()methodtakesaStringcontainingtheURLofthedocumentwewanttogetWestartbycreatingaStringBuffertoholdthelinesofthedocumentNext,wecreateanewURLwiththeurlStringwepassedinThenwecreateaURLConnectionandopenit:URLConnectionconn=urlopenConnection()PresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPageOncewehaveaURLConnection,wegetitsInputStreamandwrapitinanInputStreamReader,whichwethenwrapinaBufferedReadersothatwecanreadlinesofthedocumentwe'regettingfromtheserverWe'llusethiswrappingtechniqueoftenwhendealingwithsocketsinJavacode,butwewon'talwaysdiscussitindetailYoushouldbefamiliarwithitbeforewemoveon:BufferedReaderreader=newBufferedReader(newInputStreamReader(conngetInputStream()))HavingourBufferedReadermakesreadingthecontentsofourdocumenteasyWecallreadLine()onreaderinawhileloop:Stringline=while((line=readerreadLine())!=)documentappend(line"n")ThecalltoreadLine()isgoingtoblockuntilinreachesalineterminationcharacter(forexample,anewlinecharacter)intheincomingbytesontheInputStreamIfitdoesn'tgetone,itwillkeepwaitingItwillreturnonlywhentheconnectionisclosedInthiscase,oncewegetaline,weappendittotheStringBuffercalleddocument,alongwithanewlinecharacterThispreservestheformatofthedocumentthatwasreadontheserversideWhenwe'redonereadinglines,weclosetheBufferedReader:readerclose()IftheurlStringsuppliedtoaURLconstructorisinvalid,aMalformedURLExceptionisthrownIfsomethingelsegoeswrong,suchaswhengettingtheInputStreamontheconnection,anIOExceptionisthrownWrappingupBeneaththecovers,URLConnectionusesasockettoreadfromtheURLwespecified(whichjustresolvestoanIPaddress),butwedon'thavetoknowaboutitandwedon'tcareButthere'smoretothestorywe'llgettothatshortlyBeforewemoveon,let'sreviewthestepstocreateanduseaURLConnection:InstantiateaURLwithavalidURLStringoftheresourceyou'reconnectingto(throwsaMalformedURLExceptionifthere'saproblem)OpenaconnectiononthatURLWraptheInputStreamforthatconnectioninaBufferedReadersoyoucanreadlinesReadthedocumentusingyourBufferedReaderCloseyourBufferedReaderYoucanfindthecompletecodelistingforURLClientatCodelistingforURLClientonpagePresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPageSectionAsimpleexampleBackgroundTheexamplewe'llcoverinthissectionillustrateshowyoucanuseSocketandServerSocketinyourJavacodeTheclientusesaSockettoconnecttoaserverTheserverlistensonportwithaServerSocketTheclientrequeststhecontentsofafileontheserver'sC:driveForthesakeofclarity,wesplittheexampleintotheclientsideandtheserversideAttheend,we'llputitalltogethersoyoucanseetheentirepictureWedevelopedthiscodeinIBMVisualAgeforJava,whichusesJDKTocreatethisexampleforyourself,JDKorgreatershouldbefineTheclientandtheserverwillrunonasinglemachine,sodon'tworryabouthavinganetworkavailableCreatingtheRemoteFileClientclassHereisthestructurefortheRemoteFileClientclass:importjavaio*importjavanet*publicclassRemoteFileClient{protectedStringhostIpprotectedinthostPortprotectedBufferedReadersocketReaderprotectedPrintWritersocketWriterpublicRemoteFileClient(StringaHostIp,intaHostPort){hostIp=aHostIphostPort=aHostPort}publicstaticvoidmain(Stringargs){}publicvoidsetUpConnection(){}publicStringgetFile(StringfileNameToGet){}publicvoidtearDownConnection(){}}FirstweimportjavanetandjavaioThejavanetpackagegivesyouthesockettoolsyouneedThejavaiopackagegivesyoutoolstoreadandwritestreams,whichistheonlywayyoucancommunicatewithTCPsocketsWegiveourclassinstancevariablestosupportreadingfromandwritingtosocketstreams,andtostoredetailsoftheremotehosttowhichwewillconnectTheconstructorforourclasstakesanIPaddressandaportnumberforaremotehostandassignsthemtoinstancevariablesOurclasshasamain()methodandthreeothermethodsWe'llgointothedetailsofthesemethodslaterFornow,justknowthatsetUpConnection()willconnecttotheremoteserver,getFile()willasktheremoteserverforthecontentsoffileNameToGet,andPresentedbydeveloperWorks,yoursourceforgreattutorialsibmcomdeveloperWorksJavasocketsPagetearDownConnection()willdisconnectfromtheremoteserverImplementingmain()Hereweimplementthemain()method,whichwillcreatetheRemoteFileClient,useittogetthecontentsofaremotefile,andthenprinttheresult:publicstaticvoidmain(Stringargs){RemoteFileClientremoteFileClient=newRemoteFileClient("",)remoteFileClientsetUpConnection()StringfileContents=remoteFileClientgetFile("C:WINNTTempRemoteFiletxt")remoteFileClienttearDownConnection()Systemoutprintln(fileContents)}Themain()methodinstantiatesanewRemoteFileClient(theclient)withanIPaddressandportnumberforthehostThen,wetelltheclienttosetupaconnectiontothehost(moreonthislater)Next,wetelltheclienttogetthecontentsofaspecifiedfileonthehostFinally,wetelltheclienttoteardownitsconnectiontothehostWeprintoutthecontentsofthefiletotheconsole,justtoproveeverythingworkedasplannedSettingupaconnectionHereweimplementthesetUpConnection()method,whichwillsetupourSocketandgiveusac

类似资料

编辑推荐

Vowels and consonants Ladefoged.2001..pdf

10kV--66kV消弧线圈装置技术标准(附编制说明).pdf

Tone (Cambridge Textbooks in Linguistics)Moria Yip,PDF.pdf

策反在子夜.pdf

不轻蔑自己-格林兄弟传.pdf

职业精品

精彩专题

上传我的资料

精选资料

热门资料排行换一换

  • 灵地的缅想.pdf

  • 林非论散文.pdf

  • 李定信 天玉经房份之法.doc

  • 周易古经今注(重订本).pdf

  • 射线检测技术.ppt

  • 激光全息检测技术.ppt

  • 红外光谱分析.ppt

  • Routledge - Mode…

  • 电力预算定额2006 第五册 加…

  • 资料评价:

    / 36
    所需积分:0 立即下载

    意见
    反馈

    返回
    顶部