是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx
《是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx》由会员分享,可在线阅读,更多相关《是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx(12页珍藏版)》请在冰豆网上搜索。
![是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx](https://file1.bdocx.com/fileroot1/2023-1/24/9589fedf-a9dd-4e10-a746-d28a302e290c/9589fedf-a9dd-4e10-a746-d28a302e290c1.gif)
serveracceptstheconnection,adialogcanbeginwithbetweentheclientandtheserver.
Oncetheclientisdonewithwhateveritneedstodoitcanclosetheconnectionwiththeserver.Connectionsareexpensiveinthesensethatserversallowfiniteconnectionstooccur.
Duringthetimeclienthasanactiveconnectionitcansendthedatatotheserverand/orreceivethedata.
Thecomplexitybeginshere.Wheneitherside(clientorserver)sendsdatatheothersideissupposedtoreadthedata.Buthowwilltheothersideknowwhendatahasarrived.Therearetwooptions-eithertheapplicationneedstopollforthedataatregularintervalsorthereneedstobesomesortofmechanismthatwouldenableapplicationtogetnotificationsandapplicationcanreadthedataatthattime.Well,afterallWindowsisaneventdrivensystemandthenotificationsystemseemsanobviousandbestchoiceanditinfactis.
AsIsaidthetwoapplicationsthatneedtocommunicatewitheachother
needtomakeaconnectionfirst.Inorderforthetwoapplicationtomakeconnectionsthetwoapplicationsneedtoidentifyeachother(oreachother'
scomputer).Computersonnetworkhaveauniqueidentifiercalled
I.P.addresswhichisrepresentedindot-notationlike10.20.120.127etc.Letsseehowallthisworksin.NET.
System.Net.SocketsNamespace
Beforewegoanyfurther,downloadthesourcecodeattachedwiththisarticle.Extractthezipfiletoafoldersayc:
\Tempyouwillseefollowingtwofolders:
∙Server
∙Client
IntheServerfoldertherewillbeoneEXE.AndintheclienttherewillbethesourcecodeinC#thatisourclient.TherewillbeonefilecalledSocketClient.sln
whichthesolutionfile.IfyoudoubleclickthatyourVS.NETwillbelaunchedandyouwillseethe
projectSocketClientProjinthesolution.UnderthisprojectyouwillhaveSocketClientForm.csfile.
Nowbuildthecode(bypressingCtrl-Shift-B)andrunthecodeyouwillseethefollowingdialogbox:
AsyoucanseethedialogboxhasafieldforHostIPaddress(whichistheIPaddressofthemachineonwhichyouwillruntheServerApplication(locatedunderServerfolder)).AlsothereisafieldwhereyoucanspecifyportnumberatwhichtheServerislistening.TheserverappIhaveprovidedherelistensatport8221.SoIhavespecifiedporttobe8221.
Afterspecifyingtheseparametersweneedtoconnecttotheserver.SopressingConnectwillconnecttotheserverandtoclosetheconnectionpressClose.TosendsomedatatotheservertypesomedatainthefieldnearthebuttonnameTxandifyoupressRxtheapplicationwillblockunlessthereissomedatatoread.
Withthisinfoletsnowtrytocheckthecodebehindthis:
Socketprogrammingin.NETismadepossiblebySocketclasspresentinsidetheSystem.Net.Socketsnamespace.
Socketclass
hasseveralmethodandpropertiesandaconstructor.
Thefirststepistocreateanobjectofthisclass.
Sincethereisonlyoneconstructorwehavenochoicebuttouseit.
Hereishowtocreatethesocket:
m_socListener=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP);
ThefirstparameteristheaddressfamilywhichwewilluseinterNetwork-otheroptionsincludeBanyanNetBiosetc.
AddressFamilyisanenumdefinedinSocketsnamespace.
Nextweneedtospecifysockettype:
andwewouldusereliabletwowayconnection-basedsockets(stream)insteadofun-reliableConnectionlesssockets(datagrams).SoweobviouslyspecifystreamasthesockettypeandfinallyweareusingTCP/IPsowewouldspecifyprotocoltypeasTcp.
OncewehavecreatedaSocketweneedtomakeaconnectiontotheserversinceweareusingconnection-basedcommunication.
Toconnecttotheremotecomputer
weneedtoknowtheIPAddressandportatwhichtoconnect.
In.NETthereisaclassunderSystem.NetnamespacecalledIPEndPointwhichrepresentsanetworkcomputer
asanIPaddressandaportnumber.
TheIPEndPointhastwo
constructors-onethattakesaIPAddressandPortnumber
andonethattakeslongandportnumber.SincewehavecomputerIPaddresswewouldusetheformer
publicIPEndPoint(System.Net.IPAddressaddress,intport);
AsyoucanseethefirstparametertakesaIPAddressobject.IfyouexaminetheIPAddressclassyouwillseethatithasastaticmethodcalledParsethatreturnsIPAddressgivenastring(ofdotnotation)andsecondparameterwillbetheportnumber.OncewehaveendpointreadywecanuseConnectmethodofSocketclasstoconnecttotheendpoint
(remoteservercomputer).
Hereisthecode:
System.Net.IPAddressipAdd=System.Net.IPAddress.Parse("
10.10.101.200"
);
System.Net.IPEndPointremoteEP=newIPEndPoint(iAdd,8221);
m_socClient.Connect(remoteEP);
ThesethreelinesofcodewillmakeaconnectiontotheremotehostrunningoncomputerwithIP10.10.101.200andlisteningatport8221.IftheServerisrunningandstarted(listening),theconnectionwillsucceed.IfhowevertheserverisnotrunninganexceptioncalledSocketExceptionwillbethrown.Ifyoucatchthe
exceptionandchecktheMessagepropertyoftheexceptioninthiscaseyouseefollowingtext:
"
Noconnectioncouldbemadebecausethetargetmachineactivelyrefusedit."
Similarlyifyoualreadyhavemadeaconnectionandtheserversomehowdies,youwillgetfollowingexceptionifyoutrytosenddata.
Anexistingconnectionwasforciblyclosedbytheremotehost"
Assumingthattheconnectionismade,youcansenddatatoothersideusingtheSendmethodoftheSocketclass.
Sendmethodhasseveraloverloads.Allofthemtakeabytearray.Forexampleifyouwanttosend"
HelloThere"
tohostyoucanusefollowingcall:
try
{
StringszData="
;
byte[]byData=System.Text.Encoding.ASCII.GetBytes(szData);
m_socClient.Send(byData);
}
catch(SocketExceptionse)
MessageBox.Show(se.Message);
NotethattheSendmethodisblocking.Whatitmeansthecallwillblocktillthedatahasbeensentoranexceptionhasbeenthrown.Thereisannon-blockingversionofthesendwhichwewilldiscussinthenextpartofthisarticle.
SimilartoSendthereisaReceivemethodontheSocketclass.Youcanreceivedatausingfollowingcall:
byte[]buffer=newbyte[1024];
intiRx=m_socClient.Receive(buffer);
TheReceivemethodagainisblocking.Itmeansthatifthereisnodataavailablethecallwillblockuntilsomedataarrivesoran
exception
isthrown.
Non-blockingversionofReceivemethodismoreusefulthanthenon-blockingversionofSendbecauseifweoptforblockReceive,weareeffectivelydoingpolling.Thereisnoeventsaboutdataarrival.Thismodeldoesnotworkwellforseriousapplications.Butallthatisthesubjectofournextpartofthisarticle.Fornowwewillsettlewiththeblockingversion.
InordertousethesourcecodeandapplicationhereyouwouldneedtoruntheServerfirst:
HereisthewayServerlookslike:
WhenyoulaunchtheServer,clickStarttostartlistening.TheServerlistensatport8221.Somakesureyouspecifytheportnumber8221intheportfieldofourclientapplication.AndintheIPAddressfieldofClientAppentertheIPAddressofthemachineonwhichtheServerisrunning.IfyousendsomedatatoserverfromtheclientbypressingTxbutton,youwillseethatdatainthegrayedouteditbox.
DISCLAIMER:
ThecontentprovidedinthisarticleisnotwarrantedorguaranteedbyDeveloperShed,Inc.Thecontentprovidedisintendedforentertainmentand/oreducationalpurposesinordertointroducetothereaderkeyideas,concepts,and/orproductreviews.Assuchitisincumbentuponthereadertoemployreal-worldtacticsforsecurityandimplementationofbestpractices.Wearenotliableforanynegativeconsequencesthatmayresultfromimplementinganyinformationcoveredinourarticlesortutorials.Ifthisisahardwarereview,itisnotrecommendedtoopenand/ormodifyyourhardware.
Althoughyoucanarguethatonecanovercometheseshortcomingsbymultithreadingmeaningthatonecanspawnanewthreadandletthatthreaddothepollingandnotifiesthemainthreadofthedata.Wellthisconceptwillworkwell.ButevenifyoucreateanewthreaditwouldrequireyourmainthreadtosharetheCPUtimewiththisnewthread.Windowsoperatingsystem(WindowsNT/2000/XP)providewhatiscalledCompletionPortIOmodelfordoingoverlapped(asynchronous)IO.
ThedetailsofIOCompletionportarebeyondthescopeofthecurrentdiscussion,buttomakeitsimpleyoucanthinkofIOCompletionPortsasthemostefficientmechanismfordoingasynchronousIOinWindowsthatisprovidedbytheOperatingsystem.CompletionPortmodelcanbeappliedtoanykindofIOincludingthefileread/writ