外文翻译 - Windows 网络编程_第1页
外文翻译 - Windows 网络编程_第2页
外文翻译 - Windows 网络编程_第3页
外文翻译 - Windows 网络编程_第4页
外文翻译 - Windows 网络编程_第5页
已阅读5页,还剩14页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

0外文原文NETWORKPROGRAMMINGFORMICROSOFTWINDOWS1IntroductiontoWinsockThischapterisdedicatedtolearningthebasictechniquesforwritingsuccessfulWinsockapplications.Winsockisastandardapplicationprogramminginterface(API)thatallowstwoormoreapplications(orprocesses)tocommunicateeitheronthesamemachineoracrossanetworkandisprimarilydesignedtofosterdatacommunicationoveranetwork.ItisimportanttounderstandthatWinsockisanetworkprogramminginterfaceandnotaprotocol.WinsockprovidestheprogramminginterfaceforapplicationstocommunicateusingpopularnetworkprotocolssuchasTransmissionControlProtocol/InternetProtocol(TCP/IP)andInternetworkPacketExchange(IPX).TheWinsockinterfaceinheritsagreatdealfromtheBSDSocketsimplementationonUNIXplatforms.InWindowsenvironments,theinterfacehasevolvedintoatrulyprotocol-independentinterface,especiallywiththereleaseofWinsock2.Inthischapter,welllookatthefundamentalsofsettingupcommunicationfromonemachineonanetworktoanother,alongwithhowtosendandreceivedata.TheexamplespresentedinthischapterhelptoprovideanunderstandingoftheWinsockcallsthatarerequiredforacceptingconnections,establishingconnections,andsendingandreceivingdata.BecausethepurposeofthischapteristolearnthesefundamentalWinsockcalls,theexamplespresentedusestraightblockingWinsockcalls.Chapter5presentsnon-blockingandotheradvancedI/OmethodsavailableinWinsock,includingcodeexamples.Inaddition,inthischapterwewillpresentboththeWinsock1andWinsock2versionsofthevariousAPIfunctions.YoucandifferentiatethetwofunctionswiththeWSAprefix.IfWinsock2updatedoraddedanewAPIfunctioninitsspecification,thefunctionnameisprefixedwithWSA.Forexample,theWinsock1functiontocreateasocketissimplysocket.Winsock2introducesanewerversionnamedWSASocketthatiscapableofusingsomeofthenewfeaturesmadeavailableinWinsock2.Thereareafewexceptionstothisnaming1rule.WSAStartup,WSACleanup,WSARecvEx,andWSAGetLastErrorareintheWinsock1.1specification.BeforeyoubegindevelopinganapplicationusingWinsock,youneedtounderstandwhatfilesandlibrariesarerequiredtobuildyourapplication.1.1WinsockHeadersandLibrariesAsmentionedpreviously,WinsockisavailableintwomajorversionsWinsock1andWinsock2onallWindowsplatformsexceptWindowsCE(WindowsCEhasonlyWinsock1).WhendevelopingnewapplicationsyoushouldtargettheWinsock2specificationbyincludingWINSOCK2.Hinyourapplication.ForcompatibilitywitholderWinsockapplicationsandwhendevelopingonWindowsCEplatforms,WINSOCK.Hisavailable.Thereisalsoanadditionalheaderfile:MSWSOCK.H,whichtargetsMicrosoft-specificprogrammingextensionsthatarenormallyusedfordevelopinghighperformanceWinsockapplications,whichwillbedescribedinChapter6.WhencompilingyourapplicationwithWINSOCK2.H,youshouldlinkwithWS2_32.LIBlibrary.WhenusingWINSOCK.H(asonWindowsCE)youshoulduseWSOCK32.LIB.IfyouuseextensionAPIsfromMSWSOCK.H,youmustalsolinkwithMSWSOCK.DLL.Onceyouhaveincludedthenecessaryheaderfilesandlinkenvironment,youarereadytobegincodingyourapplication,whichrequiresinitializingWinsock.1.2InitializingWinsockEveryWinsockapplicationmustloadtheappropriateversionoftheWinsockDLL.IfyoufailtoloadtheWinsocklibrarybeforecallingaWinsockfunction,thefunctionreturnsaSOCKET_ERROR;theerrorwillbeWSANOTINITIALISED.LoadingtheWinsocklibraryisaccomplishedbycallingtheWSAStartupfunction,whichisdefinedasintWSAStartup(WORDwVersionRequested,LPWSADATAlpWSAData);ThewVersionRequestedparameterisusedtospecifytheversionoftheWinsocklibraryyouwanttoload.Thehigh-orderbytespecifiestheminorversionoftherequestedWinsocklibrary,whilethelow-orderbyteisthemajorversion.Youcanusethehandymacro2MAKEWORD(x,y),inwhichxisthehighbyteandyisthelowbyte,toobtainthecorrectvalueforwVersionRequested.ThelpWSADataparameterisapointertoaLPWSADATAstructurethatWSAStartupfillswithinformationrelatedtotheversionofthelibraryitloads:typedefstructWSADataWORDwVersion;WORDwHighVersion;charszDescriptionWSADESCRIPTION_LEN+1;charszSystemStatusWSASYS_STATUS_LEN+1;unsignedshortiMaxSockets;unsignedshortiMaxUdpDg;charFAR*lpVendorInfo;WSADATA,*LPWSADATA;WSAStartupsetsthefirstfield,wVersion,totheWinsockversionyouwillbeusing.ThewHighVersionparameterholdsthehighestversionoftheWinsocklibraryavailable.Rememberthatinbothofthesefields,thehigh-orderbyterepresentstheWinsockminorversion,andthelow-orderbyteisthemajorversion.TheszDescriptionandszSystemStatusfieldsaresetbytheparticularimplementationofWinsockandarentreallyuseful.Donotusethenexttwofields,iMaxSocketsandiMaxUdpDg.Theyaresupposedtobethemaximumnumberofconcurrentlyopensocketsandthemaximumdatagramsize;however,tofindthemaximumdatagramsizeyoushouldquerytheprotocolinformationthroughWSAEnumProtocols(seeChapter2).Themaximumnumberofconcurrentsocketsisntsomemagicnumberitdependsmoreonthephysicalresourcesavailable.Finally,thelpVendorInfofieldisreservedforvendor-specificinformationregardingtheimplementationofWinsock.ThisfieldisnotusedonanyWindowsplatforms.Table1-1liststheversionsofWinsockthatthevariousMicrosoftWindowsplatformssupport.Whatsimportanttorememberisthedifferencebetweenmajorversions.WINSOCK1.xdoesnotsupportmanyoftheadvancedWinsockfeaturesdetailedinthissection.3Table1-1SupportedWinsockVersionsPlatformWinsockVersionWindows951.1(2.2)Windows982.2WindowsMe2.2WindowsNT4.02.2Windows20002.2WindowsXP2.2NotethateventhoughaplatformsupportsWinsock2,youdonothavetorequestthelatestversion.Thatis,ifyouwanttowriteanapplicationthatissupportedonamajorityofplatforms,youshouldwriteittotheWinsock1.1specification.ThisapplicationwillrunperfectlywellonWindowsNT4.0becauseallWinsock1.1callsaremappedthroughtheWinsock2DLL.Also,ifanewerversionoftheWinsocklibrarybecomesavailableforaplatformthatyouuse,itisofteninyourbestinteresttoupgrade.Thesenewversionscontainbugfixes,andyouroldcodeshouldrunwithoutaproblematleasttheoretically.Insomecases,theWinsockstacksbehaviorisdifferentfromwhatthespecificationdefines.Asaresult,manyprogrammerswritetheirapplicationsaccordingtothebehavioroftheparticularplatformtheyaretargetinginsteadofthespecification.Forthemostpart,whenwritingnewapplicationsyouwillloadthelatestversionoftheWinsocklibrarycurrentlyavailable.Rememberthatif,forexample,Winsock3isreleased,yourapplicationthatloadsversion2.2shouldrunasexpected.IfyourequestaWinsockversionlaterthanthatwhichtheplatformsupports,WSAStartupwillfail.Uponreturn,thewHighVersionoftheWSADATAstructurewillbethelatestversionsupportedbythelibraryonthecurrentsystem.WhenyourapplicationiscompletelyfinishedusingtheWinsockinterface,youshouldcallWSACleanup,whichallowsWinsocktofreeupanyresourcesallocatedbyWinsockandcancelanypendingWinsockcallsthatyourapplicationmade.WSACleanupisdefinedasintWSACleanup(void);FailuretocallWSACleanupwhenyourapplicationexitsisnotharmfulbecausetheoperatingsystemwillfreeupresourcesautomatically;however,yourapplicationwillnotbe4followingtheWinsockspecification.Also,youshouldcallWSACleanupforeachcallthatismadetoWSAStartup.1.3ErrorCheckingandHandlingWellfirstcovererrorcheckingandhandling,astheyarevitaltowritingasuccessfulWinsockapplication.ItisactuallycommonforWinsockfunctionstoreturnanerror;however,therearesomecasesinwhichtheerrorisnotcriticalandcommunicationcanstilltakeplaceonthatsocket.ThemostcommonreturnvalueforanunsuccessfulWinsockcallisSOCKET_ERROR,althoughthisiscertainlynotalwaysthecase.WhencoveringeachAPIcallindetail,wellpointoutthereturnvaluecorrespondingtoanerror.TheconstantSOCKET_ERRORactuallyis-1.IfyoumakeacalltoaWinsockfunctionandanerrorconditionoccurs,youcanusethefunctionWSAGetLastErrortoobtainacodethatindicatesspecificallywhathappened.ThisfunctionisdefinedasintWSAGetLastError(void);Acalltothefunctionafteranerroroccurswillreturnanintegercodefortheparticularerrorthatoccurred.TheseerrorcodesreturnedfromWSAGetLastErrorallhavepredefinedconstantvaluesthataredeclaredineitherWINSOCK.HorWINSOCK2.H,dependingontheversionofWinsock.TheonlydifferencebetweenthetwoheaderfilesisthatWINSOCK2.HcontainsmoreerrorcodesforsomeofthenewerAPIfunctionsandcapabilitiesintroducedinWinsock2.Theconstantsdefinedforthevariouserrorcodes(with#definedirectives)generallybeginwithWSAE.OntheflipsideofWSAGetLastError,thereisWSASetLastError,whichallowsyoutomanuallyseterrorcodesthatWSAGetLastErrorretrieves.ThefollowingprogramdemonstrateshowtoconstructaskeletonWinsockapplicationbasedonthediscussionsofar:#includevoidmain(void)WSADATAwsaData;/InitializeWinsockversion2.2if(Ret=WSAStartup(MAKEWORD(2,2),&wsaData)!=0)5/NOTE:SinceWinsockfailedtoloadwecannotuse/WSAGetLastErrortodeterminethespecificerrorfor/whyitfailed.Insteadwecanrelyonthereturn/statusofWSAStartup.printf(WSAStartupfailedwitherror%dn,Ret);return;/SetupWinsockcommunicationcodehere/WhenyourapplicationisfinishedcallWSACleanupif(WSACleanup()=SOCKET_ERROR)printf(WSACleanupfailedwitherror%dn,WSAGetLastError();Nowwearereadytodescribehowtosetupcommunicationusinganetworkprotocol.1.4AddressingaProtocolForsimplicityssake,andtoavoidrepetition,theremainingdiscussioninthischapterislimitedtodescribinghowtomakefundamentalWinsockcallstosetupcommunicationusingtheInternetProtocol(IP).WechoseIPbecausemostWinsockapplicationsdevelopedtodayuseitbecauseitiswidelyavailableduetothepopularityoftheInternet.Aswementionedearlier,Winsockisaprotocol-independentinterfaceandspecificdetailsforusingotherprotocols,suchasIPX,arecoveredinChapter4.Also,ourdiscussionofIPinthischapterislimitedtobrieflydescribingIPversion4(IPv4).Chapter3fullydescribesallIPversionsIPv4andIPversion6(IPv6)ingreaterdetail.Throughouttheremainderofthischapter,wewilldemonstratethebasicsofhowtosetupWinsockcommunicationusingtheIPv4protocol.IPiswidelyavailableonmostcomputeroperatingsystemsandcanbeusedonmostlocalareanetworks(LANs),suchasasmallnetworkinyouroffice,andonwideareanetworks(WANs),suchastheInternet.Bydesign,IPisaconnectionlessprotocolanddoesntguaranteedatadelivery.Twohigher-levelprotocolsTransmissionControlProtocol(TCP)andUserDatagramProtocol(UDP)areusedforconnection-orientedandconnectionlessdatacommunicationoverIP,whichwewill6describelater.BothTCPandUDPuseIPfordatatransmissionandarenormallyreferredtoasTCP/IPandUDP/IP.TouseIPv4inWinsock,youneedunderstandhowtoaddressIPvAddressingIPv4InIPv4,computersareassignedanaddressthatisrepresentedasa32-bitquantity.WhenaclientwantstocommunicatewithaserverthroughTCPorUDP,itmustspecifytheserversIPaddressalongwithaserviceportnumber.Also,whenserverswanttolistenforincomingclientrequests,theymustspecifyanIPaddressandaportnumber.InWinsock,applicationsspecifyIPaddressesandserviceportinformationthroughtheSOCKADDR_INstructure,whichisdefinedasstructsockaddr_inshortsin_family;u_shortsin_port;structin_addrsin_addr;charsin_zero8;Thesin_familyfieldmustbesettoAF_INET,whichtellsWinsockweareusingtheIPaddressfamily.Thesin_portfielddefineswhichTCPorUDPcommunicationportwillbeusedtoidentifyaserverservice.Applicationsshouldbeparticularlycarefulinchoosingaportbecausesomeoftheavailableportnumbersarereservedforwell-knownservices,suchasFileTransferProtocol(FTP)andHypertextTransferProtocol(HTTP).TherearemoredetailsaboutchoosingaportinChapter2.Thesin_addrfieldoftheSOCKADDR_INstructureisusedforstoringanIPv4addressasafour-bytequantity,whichisanunsignedlongintegerdatatype.Dependingonhowthisfieldisused,itcanrepresentalocaloraremoteIPaddress.IPaddressesarenormallyspecifiedinInternetstandarddottednotationas“a.b.c.d.”Eachletterrepresentsanumber(indecimal,octal,orhexadecimalformat)foreachbyteandisassigned,fromlefttoright,tothefourbytesoftheunsignedlonginteger.Thefinalfield,sin_zero,functionsonlyaspaddingtomaketheSOCKADDR_INstructurethesamesizeastheSOCKADDRstructure.7Ausefulsupportfunctionnamedinet_addrconvertsadottedIPaddresstoa32-bitunsignedlongintegerquantity.Theinet_addrfunctionisdefinedasunsignedlonginet_addr(constcharFAR*cp);Thecpfieldisanull-terminatedcharacterstringthatacceptsanIPaddressindottednotation.NotethatthisfunctionreturnsanIPaddressasa32-bitunsignedlongintegerinnetwork-byteorder.1.4.2ByteOrderingDifferentcomputerprocessorsrepresentnumbersinbig-endianandlittle-endianform,dependingonhowtheyaredesigned.Forexample,onIntelx86processors,multibytenumbersarerepresentedinlittle-endianform:thebytesareorderedfromleastsignificanttomostsignificant.WhenanIPaddressandportnumberarespecifiedasmultibytequantitiesinacomputer,theyarerepresentedinhost-byteorder.However,whenIPaddressesandportnumbersarespecifiedoveranetwork,Internetnetworkingstandardsspecifythatmultibytevaluesmustberepresentedinbig-endianform(mostsignificantbytetoleastsignificant),normallyreferredtoasnetwork-byteorder.Aseriesoffunctionscanbeusedtoconvertamultibytenumberfromhost-byteordertonetwork-byteorderandviceversa.ThefollowingfourAPIfunctionsconvertanumberfromhost-bytetonetwork-byteorder:u_longhtonl(u_longhostlong);intWSAHtonl(SOCKETs,u_longhostlong,u_longFAR*lpnetlong);u_shorthtons(u_shorthostshort);intWSAHtons(SOCKETs,u_shorthostshort,8u_shortFAR*lpnetshort);ThehostlongparameterofhtonlandWSAHtonlisafour-bytenumberinhost-byteorder.Thehtonlfunctionreturnsthenumberinnetwork-byteorder,whereastheWSAHtonlfunctionreturnsthenumberinnetwork-byteorderthroughthelpnetlongparameter.ThehostshortparameterofhtonsandWSAHtonsisatwo-bytenumberinhost-byteorder.Thehtonsfunctionreturnsthenumberasatwo-bytevalueinnetwork-byteorder,whereastheWSAHtonsfunctionreturnsthenumberthroughthelpnetshortparameter.Thenextfourfunctionsaretheoppositeoftheprecedingfourfunctions;theyconvertnetwork-byteordertohost-byteorder.u_longntohl(u_longnetlong);intWSANtohl(SOCKETs,u_longnetlong,u_longFAR*lphostlong)u_shortntohs(u_shortnetshort);intWSANtohs(SOCKETs,u_shortnetshort,u_shortFAR*lphostshort);WenowdemonstratehowtoaddressIPv4bycreatingaSOCKADDR_INstructureusingtheinet_addrandhtonsfunctionsdescribedpreviously.SOCKADDR_INInternetAddr;INTnPortId=5150;InternetAddr.sin_family=AF_INET;/ConverttheproposeddottedInternetaddress9/toafour-byteinteger,andassignittosin_addr9InternetAddr.sin_addr.s_addr=inet_addr(9);/ThenPortIdvariableisstoredinhost-byteorder.Convert/nPortIdtonetwork-byteorder,andassignittosin_port.InternetAddr.sin_port=htons(nPortId);Asyoucanprobablytell,IPaddressesarenteasytoremember.Mostpeoplewouldmuchratherrefertoamachine(orhost)byusinganeasy-to-remember,user-friendlyhostnameinsteadofanIPaddress.Chapter3describesusefuladdressandnameresolutionfunctionsthatcanhelpyouresolveahostname,,toanIPaddressandaservicename,suchasFTP,toaportnumberusingfunctionssuchasgetaddrinfo,getnameinfo,gethostbyaddr,gethostbyname,gethostname,getprotobyname,getprotobynumber,get-servbyname,andgetservbyport.Therearealsosomeasynchronousversionsofsomeofthesefunctions:wsaasyncgethostbyaddr,wsaasyncgethostbyname,wsaasyncgetprotobyname,wsaasyncgetprotobynumber,wsaasyncgetservbyandwsaasyncgetservbyport.NowthatyouhavethebasicsofaddressingaprotocolsuchasIPv4,youcanpreparetosetupcommunicationbycreatingasocket.1.5CreatingaSocketIfyourefamiliarwithWinsock,youknowthattheAPIisbasedontheconceptofasocket.Asocketisahandletoatransportprovider.InWindows,asocketisnotthesamethingasafiledescriptorandthereforeisaseparatetype:SOCKETinWINSOCK2.H.Therearetwofunctionsthatcanbeusedtocreateasocket:socketandWSASocket.Thenextthreechaptersdescribesocketcreationforeachoftheavailableprotocolsingreatdetail.Forsimplicity,wewillbrieflydescribesocket:SOCKETsocket(intaf,inttype,intprotocol);Thefirstparameter,af,istheprotocolsaddressfamily.SincewedescribeWinsockinthischapterusingonlytheIPv4protocol,youshouldsetthisfieldtoAF_INET.Thesecondparameter,type,istheprotocolssockettype.WhenyouarecreatingasockettouseTCP/IP,10setthisfieldtoSOCK_STREAM,forUDP/IPuseSOCK_DGRAM.Thethirdparameterisprotocolandisusedtoqualifyaspecifictransportiftherearemultipleentriesforthegivenaddressfamilyandsockettype.ForTCPyoushouldsetthisfieldtoIPPROTO_TCP;forUDPuseIPPROTO_UDP.Chapter2describessocketcreationingreaterdetailforallprotocols,includingtheWSASocketAPI.Winsockfeaturesfourusefulfunctionstocontrolvarioussocketoptionsandsocketbehaviors:setsockopt,getsockopt,ioctlsocket,andWSAIoctl.ForsimpleWinsockprogramming,youwillnotneedtousethemspecifically.Chapter7describeseachofthesefunctionsandalltheavailableoptions.Onceyouhavesuccessfullycreatedasocket,youarereadytosetupcommunicationonthesockettoprepareitforsendingandreceivingdata.InWinsocktherearetwobasiccommunicationtechniques:connection-orientedandconnectionlesscommunication.1.6Connection-OrientedCommunicationInthissection,wellcovertheWinsockfunctionsnecessaryforbothreceivingconnectionsandestablishingconnections.Wellfirstdiscusshowtodevelopaserverbylisteningforclientconnectionsandexploretheprocessforacceptingorrejectingaconnection.Thenwelldescribehowtodevelopaclientbyinitiatingaconnectiontoaserver.Finally,welldiscusshowdataistransferredinaconnection-orientedsession.InIP,connection-orientedcommunicationisaccomplishedthroughtheTCP/IPprotocol.TCPprovidesreliableerror-freedatatransmissionbetweentwocomputers.WhenapplicationscommunicateusingTCP,avirtualconnectionisestablishedbetweenthesourcecomputerandthedestinationcomputer.Onceaconnectionisestablished,datacanbeexchangedbetweenthecomputersasatwo-waystreamofbytes.11外文原文翻译Windows网络编程1Winsock简介本章专门讲解编写成功的Winsock应用程序的基本方法。Winsock是一种标准API(applicationprogramminginterface,应用程序编程借口),主要用于网络中的数据通信,它允许两个或者多个应用程序(或过程)在同一台机器上或通过网络相互通信。有一点我们必须明白:Winsock是一种网络编程接口,而不是协议。使用Winsock编程接口,应用程序可通过普通网络协议如TCP/IP(TransmissionControlProtocol/InternetProtocol,传输控制协议/网际协议)或IPX(InternetPacketExchange,Internet数据包交换)协议建立通信。Winsock接口从在UNIX平台上实现的BSDSocket(套接字)中继承了大量的特性。在Windows环境下,这种接口演变成一种真正独立于协议的接口,新发布的Winsock2版本更是如此。本章将讨论从网络上的一台机器到另一台机器建立通信的基本知识,以及如何发送和接收数据。为了便于大家理解接受连接、建立连接和收发数据所需的Winsock调用,本章给出了多个示例。由于本章的目的是学习这些基本的Winsock调用,因而所举的示例均采用了直接阻塞的Winsock调用。第5章将讲述Winsock支持的非阻塞调用及其他各种I/O方法,其中包含示例代码。除此以外,本章还将介绍各种API函数的Winsock1和Winsock2版本。通过前缀WSA可以区分该函数的两种版本。若Winsock2在其规范中更新或添加一个新的API函数,该函数名将带有WSA前缀。比如,建立套接字WinSock1函数只是简单成为socket,而Winsock2引入该函数的新版本时,则将它命名为WSASocket,该函数可以使用Winsock2中出现的一些新特性。但请注意:这个命名规则有几个例外,如WSAStartup、WSACleanup、WSARecvEx及WSAGetLastError都属于Winsock1.1规范的函数。在使用Winsock开发应用程序之前,必须了解创建应用程序时需要哪些文件和库。1.1Winsock头文件及库文件如前所述,Winsock有两个主要版本,即Winsock1和Winsock2,两者都能在除WindowsCE之外(WindowsCE只支持Winsock1)的所有Windows平台上运行。开发新的应用程序时,把WINS

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

最新文档

评论

0/150

提交评论