首页 > > > socket开发指南.pdf

socket开发指南.pdf

socket开发指南.pdf

上传者: 413219252 2011-08-01 评分1 评论0 下载637 收藏10 阅读量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

精彩专题

热门资料

[游戏感:虚拟感觉的游戏设计师指南].pdf

[游戏开发大全(game.programming.all.in.one)].pdf

Rootkits_Windows内核的安全防护.pdf

浪潮之巅.pdf

该用户的其他资料

  • 名称/格式
  • 评分
  • 下载次数
  • 资料大小
  • 上传时间

用户评论

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

相关资料换一换

资料评价:

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

温馨提示

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