是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx

上传人:b****5 文档编号:20593502 上传时间:2023-01-24 格式:DOCX 页数:12 大小:47.39KB
下载 相关 举报
是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx_第1页
第1页 / 共12页
是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx_第2页
第2页 / 共12页
是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx_第3页
第3页 / 共12页
是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx_第4页
第4页 / 共12页
是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx_第5页
第5页 / 共12页
点击查看更多>>
下载资源
资源描述

是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx

《是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx》由会员分享,可在线阅读,更多相关《是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx(12页珍藏版)》请在冰豆网上搜索。

是服务器端套接字并不定位具体的客户端套接字而是处文档格式.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 农林牧渔 > 林学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1