網(wǎng)絡(luò)編程2013寫一個簡單客戶端服務(wù)器端交互程序_第1頁
網(wǎng)絡(luò)編程2013寫一個簡單客戶端服務(wù)器端交互程序_第2頁
網(wǎng)絡(luò)編程2013寫一個簡單客戶端服務(wù)器端交互程序_第3頁
網(wǎng)絡(luò)編程2013寫一個簡單客戶端服務(wù)器端交互程序_第4頁
網(wǎng)絡(luò)編程2013寫一個簡單客戶端服務(wù)器端交互程序_第5頁
已閱讀5頁,還剩47頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

NetworkIntroductiontoComputerSystems24thLecture,Dec.12,2013XiangqunChen,JunlinLuReviewof ,connection,portRevisitof -serverSocketinterface,EchosideServersideTestofEchoAProgrammer’sViewoftheHostsaremappedtoasetof32-bitIPThesetofIPaddressesismappedtoasetofidentifierscalledInte names79ismappedAprocessononeInte hostcancommunicatewithaprocessonanotherInte hostoveraconnection AsocketisanendpointofaAportisa16-bitintegerthatidentifiesaEphemeralport:AssignedautomaticallyandtemporarilyonwhenmakesaconnectionrequestWell-knownport:port80isassociatedwithWebAconnectionisuniquelyidentifiedbythesocketaddressesofidpoints(socketpair)(cliaddr:cliport,PuttingitallAnatomyofan socketaddress

Serversockethostaddress

51213isanephemeralportallocatedbythekernel

80isawell-knownportReviewof ,connection,portRevisitof -serverSocketinterface,EchosideServersideTestofEcho -Server sends4.

sends Note:sandserversareprocessesrunningonhosts(canbethesameordifferenthosts) workapplicationsarebasedonthe-serverServerhandlerequestforresourcesExamplesofWebbrowsers, net,Howdoes findtheserver?IPaddr:portTheIPaddressintheserversocket entifiesthe(moreprecisely,anadapterontheThe(well-known)portintheserversocketaddre entifiestheservice,andthusimplicitlyidentifiestheserverprocessthatperformsthatservice.ExamplesofwellknowPort7:EchoPort23:netPort25:MailPort80:WebUsingPortstoIdentifyServerhosthost

(i.e.,theWeb

(port80)(port7)(i.e.,theecho(portEcho(port Serversarelong-runningprocesses(daemons程序Createdatboot-time(typically)bytheinitprocess(processRuncontinuouslyuntilthemachineisturnedEachserverwaitsforrequeststoarriveonawell-knownportassociatedwithaparticularservicePort7:echoPort netPort25:mailPort80:HTTPAmachhatrunsaserverprocessisalsooftenreferredasaServerWebserver(portResource:files/computecycles(CGIService:retrievesfilesandrunsCGIprogramsonbehalfofSee/etc/servicesforacomprehensivelistofSee/etc/servicesforacomprehensivelistoftheport sonaLinuxResource:Service:storesandretrievenetserverResource:Service:proxiesaterminalontheserverMailserver “spool”Service:storesmailmessagesinspoolReviewof ,connection,portRevisitof -serverSocketinterface,EchosideServersideTestofEchoSocketsCreatedintheearly80’saspartoftheoriginalBerkeleydistributionofUnixthatcontainedanearlyversionofthe Providesauser-levelinterfaceto Underlyingbasisforall Basedon/serverprogrammingsocket Connect(IPaddr,port

Whatisa

Tothekernel,asocketisanendpointofToanapplication,asocketisafiledescriptorthatletstheapplicationread/writefrom/toth wrRemember:AllUnixI/Odevices,ludinworks,modeledas sandserverscommunicatewitheachotherbyreadingfromandwritingtosocketdescriptorsThemaindisttionbetweenregularfileI/OandsocketI/Oishowtheapplication“opens”thesocketdescriptorsOverviewoftheSockets Server打開 發(fā) 等/

requestfromnextSocketAddressGenericsocketForaddressargumentstoconnect,bind,andNecessaryonlybecauseCdidnothavegeneric(void*)pointerswhenthesocketsinterfacewasdesignedstructstruct{short/*protocolfamily/*addressSocketAddress -specificsocketMustcast(sockaddr_in*)to(sockaddr*)forconnect,bind,andacceptstructstructsockaddr_inunsignedshortunsignedshortstructin_addrunsignedchar/*addressfamily(always)/*portnum/*IPaddrworkbyteorderworkbyteorder*/sin_zero[8];/*padtosizeof(structsockaddr)*/ 00000000Example:Echoandgreatwhite>./echoserverigreatwhite>./echoserverilinux>serverconnectedserverconnectedtoBRYANT-TP4.VLSI.CS.CMU.EDU(9),port64690oserverreceived12type:OConnectionReviewof ,connection,portRevisitof -serverSocketinterface,EchosideServersideTestofEcho

EchoMain lude/*usage:./echo hostport*/intmain(intargc,char**argv){ fd,char*host,buf[MAXLINE];rio_trio;host=argv[1];port=fd=Open_fd(host,

Sendlo

printf("type:");while(Fgets(buf,MAXLINE,stdin)!=NULL) fd,buf,from Rio_readlineb(&rio,buf,Fputs(buf,stdout);printf("type:");

} Connect在 fd函數(shù) OverviewoftheSockets Server

:open_int fd(char*hostname,int{int structhostent*hp;structsockaddr_in

Thisfunctionopensaconnectionfromthetotheserveratif(( fd=socket(AF_ ,SOCK_STREAM,0))<0)return-1;/*checkerrnoforcauseoferror*//*Fillintheserver'sIPaddressandportif((hp=gethostbyname(hostname))==return-2;/*checkh_errnoforcauseoferror*/bzero((char*)&serveraddr,sizeof(serveraddr));serveraddr.sin_family=AF_ bcopy((char*)hp-(char*)&serveraddr.sin_addr.s_addr,hp->h_length);serveraddr.sin_port=htons(port);/*Establishaconnectionwiththeserver*/if(connect( fd,(SA*)&serveraddr,sizeof(serveraddr))<return-1; }

:open_socketcreatesasocketdescriptoronJustallocates&initializessomeinternaldata :indicatesthatthesocketisassociatedwith SOCK_STREAM:selectsareliablebytestreamfd;/*socketdescriptorif<fd=,SOCK_STREAM,return-1;/*checkerrnoforcauseoferror... :open_Thethenbuildstheserver’s /*socketdescriptorstructhostent*hp; /*DNShostentry*/structsockaddr_inserveraddr;/*server’sIPaddress*//*fillintheserver'sIPaddressandport*/if((hp=gethostbyname(hostname))==NULL)return-2;/*checkh_errnoforcauseoferror*/bzero((char*)&serveraddr,sizeof(serveraddr));serveraddr.sin_family=AF_ serveraddr.sin_port=htons(port);bcopy((char*)hp-

ACarefulLookatbcopy/*DNShostentrystructure*/structhostent{.. /*lengthofanaddress,inbytes*/ **h_addr_list;/*null-terminatedarrayofin_addrstructsstructsockaddr_in..structin_addr /*IPaddriworkbyte./*Inteaddressstructure*/structin_addr{unsignedints_addr;workbyteorder(big-endian)structstructhostent/*DNShostentrystructsockaddr_inserveraddr;/*server’ssocketaddressbcopy((char*)hp->h_addr_list[0],/*src,dest(char*)&serveraddr.sin_addr.s_addr,hp-BcopyArgumentDatastruct ..0 struct0000000000000tructs :open_Finallythecreatesaconnectionwiththeprocesssuspends(blocks)untiltheconnectionisAfterresuming,the isreadytobeginexchangingmessageswiththeserverviaUnixI/Ocallsondescriptor /*socketdescriptor*/structsockaddr_inserveraddr; /*serveraddress*/typedefstructsockaddrSA; /*genericsockaddr*//*Establishaconnectionwiththeserverif fd,(SA*)&serveraddr,sizeof(serveraddr))return-1; }Reviewof ,connection,portRevisitofa-serverSocketinterface,EchosideServersideTestofEcho

EchoServer:Mainintmain(intargc,char**argv)intlistenfd,connfd,port, structsockaddr_ structhostent*hp;char*haddrp;unsigned port=atoi(argv[1]);/*theserverlistensonaportonthecommandlinelistenfd=while(1)len= connfd=Accept(listenfd,(SA*)& addr,& hp=Gethostbyaddr((constchar*)& addr.sin_addr.s_addr),AF_ haddrp= _port=ntohs( printf("serverconnectedto%s(%s),port%u\n",hp->h_name, }}OverviewoftheSockets

Officeephoneogyfor Buya lthelocaladministratorwhatnumberyouwanttouse Plugthephone Answerthephonewhenitrings=EchoServer:intopen_listenfd(int{intlistenfd,optval=1;structsockaddr_inserveraddr;/*/*Createasocketdescriptorif((listenfd=socket(AF_return-1;,0))</*Eliminates"Addressalreadyinuse"errorfrombind.*/if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,(constvoid*)&optval,sizeof(int))<return-...EchoServer:open_listenfd/*ListenfdwillbeanendpointforallrequeststoportonanyIPaddressforthishost*/bzero((char*)&serveraddr,sizeof(serveraddr));serveraddr.sin_family=AF_ serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);serveraddr.sin_port=htons((unsignedshort)port);if(bind(listenfd,(SA*)&serveraddr,sizeof(serveraddr))return-/*Makeitalisteningsocketreadytoacceptconnectionrequests*/if(listen(listenfd,LISTENQ)<0)return-1;return}EchoServer:socketcreatesasocketdescriptoronthe :indicatesthatthesocketisassociatedwith SOCK_STREAM:selectsareliablebytestreamconnectionintintlistenfd;/*listeningsocketdescriptor/*Createasocketdescriptorif((listenfd=socket(AF_ ,SOCK_STREAM,0))<0)return-1;EchoServer:Thesocketcanbegivensome/*Eliminates"Addressalreadyinuse"errorfrombind().*/if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,(constvoid*)&optval,sizeof(int))<return- HandytrickthatallowsustoreruntheserverimmediayafterwekillitOtherwisewewouldhavetowaitabout15Eliminates“Addressalreadyinuse”errorfromStronglysuggestyoudothisforallyourserverstosimplifyEchoServer:(initializesocketInitializesocketwithserverportAcceptconnectionfromanyIPstructstructsockaddr_inserveraddr;/*server'ssocketaddr/*listenfdwillbeanendpointforallrequeststoportonanyIPaddressforthishost*/bzero((char*)&serveraddr,sizeof(serveraddr));serveraddr.sin_family=AF_ serveraddr.sin_port=htons((unsignedshort)port);serveraddr.sin_addr.s_addr=htonl(INADDR_ANY);IPaddrandportstored work(big-endian)byte ADD00000000

EchoServer:bindassociatesthesocketwiththesocketaddresswejustintlistenfd; /*listeningsocket*/structintlistenfd; /*listeningsocket*/structsockaddr_inserveraddr;/*server’ssocketaddr*//*listenfdwillbeanendpointforallrequeststoportonanyIPaddressforthishost*/if(bind(listenfd,(SA*)&serveraddr,sizeof(serveraddr))<0)return-1;EchoServer:listenindicatesthatthissocketwillacceptconnection(connect)requestsfrom LISTENQisconst dicatinghowmanypendingrequestsintintlistenfd;/*listeningsocket/*Makeitalisteningsocketreadytoacceptconnectionrequests*/if(listen(listenfd,LISTENQ)<0)return-1;returnlistenfd;}We’refinallyreadytoenterthemainserverloopthatacceptsandprocessesconnectionrequests.EchoServer:MainTheserverloopsendlessly,waitingforconnectionrequests,thenreadinginputfromthe,andechoingtheinputbacktothe.main()/*createandconfigurethelisteningsocket*/準備工作就緒:socket,open_listenfd,bindaddress+port#while(1){}Accept():waitforaconnectionrequestecho():readandechoinputlinesfrom tilEOF*/Close():closetheconnection*/}OverviewoftheSockets Server /

requestfromnextEchoServer:accept()blockswaitingforaconnectionintintlistenfd;/*listeningdescriptor*/intconnfd;/*connecteddescriptor*/structsockaddr_lientaddr;intlen=connfd=Accept(listenfd,(SA acceptreturnsaconnecteddescriptor(connfd)withthesamepropertiesasthelisteningdescriptorReturnswhentheconnectionbetweenandserveriscreatedandreadyforI/OtransfersAllI/Owiththewillbedoneviatheconnectedacceptalso lient’sIPEchoServer:accept

Serverblocksinaccept,waitingforconnectionrequestonlisteningdescriptor

makesconnectionrequestbycallingandblocking connfdServerreturnsconnfd returnsfromConnectionisnowestablishedfdandConnectedvs.ListeningListeningdescriptor一直存在=服務(wù)器時Endpoint CreatedonceandexistsforlifetimeoftheEndpointoftheconnection andAnewdescriptoriscreatedeachtimetheserveracceptsaconnectionrequestfromaExistsonlyaslongasittakestoWhythe tion?AllowsforconcurrentserversthatcancommunicateoversimultaneouslyE.g.,Eachtimewereceiveanewrequest,weforkachildtohandletherequestEchoServer:IdentifyingtheTheservercandetermhename,IPaddress,andportofthestructhost

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

最新文檔

評論

0/150

提交評論