Tải bản đầy đủ (.pdf) (1,014 trang)

2003 sybex c sharp network programming

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.86 MB, 1,014 trang )

C#NetworkProgramming
byRichardBlum
Sybex©2003(647pages)

ISBN:0782141765

Thisbookhelpsnewcomersgetstartedwith
alookatthebasicsofnetworkprogramming
astheyrelatetoC#,includingthe
language’snetworkclasses,theWinsock
interface,andDNSresolution.
TableofContents
C#NetworkProgramming
Introduction
PartI-NetworkProgrammingBasics

Chapter1
Chapter2
Chapter3
Chapter4

- TheC#Language
- IPProgrammingBasics
- C#NetworkProgrammingClasses
- DNSandC#

PartII-NetworkLayerPrograming

Chapter5 - Connection-OrientedSockets
Chapter6 - ConnectionlessSockets
Chapter7 - UsingTheC#SocketsHelperClasses


Chapter8 - AsynchronousSockets
Chapter9 - UsingThreads
Chapter10 - IPMulticasting
PartIII-ApplicationLayerProgrammingExamples

Chapter11 - ICMP
Chapter12 - SNMP
Chapter13 - SMTP


Chapter14 - HTTP
Chapter15 - ActiveDirectory
Chapter16 - Remoting
Chapter17 - Security
Index
ListofFigures
ListofTables
ListofListings
ListofSidebars


BackCover
Onitsown,C#simplifiesnetworkprogramming.
CombineitwiththepreciseinstructionfoundinC#
NetworkProgramming,andyou’llfindthatbuilding
networkapplicationsiseasierandquickerthanever.
Thisbookhelpsnewcomersgetstartedwithalookat
thebasicsofnetworkprogrammingastheyrelateto
C#,includingthelanguage’snetworkclasses,the
Winsockinterface,andDNSresolution.Spendasmuch

timehereasyouneed,thendigintothecoretopicsof
thenetworklayer.You’lllearntomakesockets
connectionsviaTCP,and“connectionless”connections
viaUDP.You’llalsodiscoverjusthowmuchhelpC#
givesyouwithsomeofyourtoughestchores,suchas
asynchronoussocketprogramming,multithreading,
andmulticasting.
Network-layertechniquesarejustameanstoanend,
ofcourse,andsothisbookkeepsgoing,providinga
seriesofdetailedapplication-layerprogramming
examplesthatshowyouhowtoworkwithreal
protocolsandrealnetworkenvironmentstobuildand
implementavarietyofapplications.UseSNMPto
managenetworkdevices,SMTPtocommunicatewith
remotemailservers,andHTTPtoWeb-enableyour
applications.AnduseclassesnativetoC#toquery
andmodifyActiveDirectoryentries.
Roundingitalloutisplentyofadvancedcoverageto
pushyourC#networkprogrammingskillstothelimit.
Forexample,you’lllearntwowaystoshareapplication


methodsacrossthenetwork:usingWebservicesand
remoting.You’llalsomasterthesecurityfeatures
intrinsictoC#and.NET—featuresthatstandtobenefit
allofyourprogrammingprojects.
AbouttheAuthor
RichardBlumhasspent14yearsasanetworkand
systemadministratorfortheUSDepartmentof
Defense,supportingalargenetworkofworkstations

andservers.HeholdsaBSinElectricalEngineering
andanMSinManagementInformationSystems,both
fromPurdueUniversity.


C#NetworkProgramming
RichardBlum
AssociatePublisher:JoelFugazzotto
AcquisitionsEditor:DeniseS.Lincoln
DevelopmentalEditor:CarolHenry
Editor:SallyEngelfried
ProductionEditor:EricaYee
TechnicalEditor:DanFrumin
GraphicIllustrator:JeffWilson,HappenstanceType-O-Rama
ElectronicPublishingSpecialists:ScottBenoit,JudyFung
Proofreaders:EmilyHsuan,DaveNash,LaurieO’Connell,Yariv
Rabinovitch,NancyRiddiough
Indexer:TedLaux
CoverDesigner:CarolGorska,GorskaDesign
CoverPhotographer:CarlosNavajas,TheImageBank
Copyright©2003SYBEXInc.,1151MarinaVillageParkway,Alameda,
CA94501.Worldrightsreserved.Nopartofthispublicationmaybe
storedinaretrievalsystem,transmitted,orreproducedinanyway,
includingbutnotlimitedtophotocopy,photograph,magnetic,orother
record,withouttheprioragreementandwrittenpermissionofthe
publisher.
LibraryofCongressCardNumber:2002111958
ISBN:0-7821-4176-5
SYBEXandtheSYBEXlogoareeitherregisteredtrademarksor
trademarksofSYBEXInc.intheUnitedStatesand/orothercountries.

ScreenreproductionsproducedwithFullShot99.FullShot99©19911999InbitIncorporated.Allrightsreserved.FullShotisatrademarkof
InbitIncorporated.
Internetscreenshot(s)usingMicrosoftInternetExplorerVersion6
reprintedbypermissionfromMicrosoftCorporation.


TRADEMARKS:SYBEXhasattemptedthroughoutthisbookto
distinguishproprietarytrademarksfromdescriptivetermsbyfollowingthe
capitalizationstyleusedbythemanufacturer.
Theauthorandpublisherhavemadetheirbesteffortstopreparethis
book,andthecontentisbaseduponfinalreleasesoftwarewhenever
possible.Portionsofthemanuscriptmaybebaseduponpre-release
versionssuppliedbysoftwaremanufacturer(s).Theauthorandthe
publishermakenorepresentationorwarrantiesofanykindwithregardto
thecompletenessoraccuracyofthecontentshereinandacceptno
liabilityofanykindincludingbutnotlimitedtoperformance,
merchantability,fitnessforanyparticularpurpose,oranylossesor
damagesofanykindcausedorallegedtobecauseddirectlyorindirectly
fromthisbook.
ManufacturedintheUnitedStatesofAmerica
10987654321
SoftwareLicenseAgreement:TermsandConditions
Themediaand/oranyonlinematerialsaccompanyingthisbookthatare
availablenoworinthefuturecontainprogramsand/ortextfiles(the
“Software”)tobeusedinconnectionwiththebook.SYBEXherebygrants
toyoualicensetousetheSoftware,subjecttothetermsthatfollow.Your
purchase,acceptance,oruseoftheSoftwarewillconstituteyour
acceptanceofsuchterms.
TheSoftwarecompilationisthepropertyofSYBEXunlessotherwise
indicatedandisprotectedbycopyrighttoSYBEXorothercopyright

owner(s)asindicatedinthemediafiles(the“Owner(s)”).Youarehereby
grantedasingle-userlicensetousetheSoftwareforyourpersonal,
noncommercialuseonly.Youmaynotreproduce,sell,distribute,publish,
circulate,orcommerciallyexploittheSoftware,oranyportionthereof,
withoutthewrittenconsentofSYBEXandthespecificcopyrightowner(s)
ofanycomponentsoftwareincludedonthismedia.
IntheeventthattheSoftwareorcomponentsincludespecificlicense
requirementsorend-useragreements,statementsofcondition,


disclaimers,limitationsorwarranties(“End-UserLicense”),thoseEndUserLicensessupersedethetermsandconditionshereinastothat
particularSoftwarecomponent.Yourpurchase,acceptance,oruseofthe
SoftwarewillconstituteyouracceptanceofsuchEnd-UserLicenses.
Bypurchase,useoracceptanceoftheSoftwareyoufurtheragreeto
complywithallexportlawsandregulationsoftheUnitedStatesassuch
lawsandregulationsmayexistfromtimetotime.
ReusableCodeinThisBook
Theauthor(s)createdreusablecodeinthispublicationexpresslyfor
reusebyreaders.Sybexgrantsreaderslimitedpermissiontoreusethe
codefoundinthispublication,andavailablefordownloadfromour
websitesolongastheauthor(s)areattributedinanyapplication
containingthereusablecodeandthecodeitselfisneverdistributed,
postedonlinebyelectronictransmission,sold,orcommerciallyexploited
asastand-aloneproduct.
SoftwareSupport
ComponentsofthesupplementalSoftwareandanyoffersassociated
withthemmaybesupportedbythespecificOwner(s)ofthatmaterial,but
theyarenotsupportedbySYBEX.Informationregardinganyavailable
supportmaybeobtainedfromtheOwner(s)usingtheinformation
providedintheappropriateread.mefilesorlistedelsewhereonthe

media.
Shouldthemanufacturer(s)orotherOwner(s)ceasetooffersupportor
declinetohonoranyoffer,SYBEXbearsnoresponsibility.Thisnotice
concerningsupportfortheSoftwareisprovidedforyourinformationonly.
SYBEXisnottheagentorprincipaloftheOwner(s),andSYBEXisinno
wayresponsibleforprovidinganysupportfortheSoftware,norisitliable
orresponsibleforanysupportprovided,ornotprovided,bytheOwner(s).
Disclaimer
SYBEXmakesnowarrantyorrepresentation,eitherexpressedor
implied,withrespecttotheSoftwareoritscontents,quality,performance,


merchantability,orfitnessforaparticularpurpose.Innoeventwill
SYBEX,itsdistributors,ordealersbeliabletoyouoranyotherpartyfor
direct,indirect,special,incidental,consequential,orotherdamages
arisingoutoftheuseoforinabilitytousetheSoftwareoritscontents
evenifadvisedofthepossibilityofsuchdamage.Intheeventthatthe
Softwareincludesanonlineupdatefeature,SYBEXfurtherdisclaimsany
obligationtoprovidethisfeatureforanyspecificdurationotherthanthe
initialposting.
Theexclusionofimpliedwarrantiesisnotpermittedbysomestates.
Therefore,theaboveexclusionmaynotapplytoyou.Thiswarranty
providesyouwithspecificlegalrights;theremaybeotherrightsthatyou
mayhavethatvaryfromstatetostate.Thepricingofthebookwiththe
SoftwarebySYBEXreflectstheallocationofriskandlimitationson
liabilitycontainedinthisagreementofTermsandConditions.
SharewareDistribution
ThisSoftwaremaycontainvariousprogramsthataredistributedas
shareware.Copyrightlawsapplytobothsharewareandordinary
commercialsoftware,andthecopyrightOwner(s)retainsallrights.Ifyou

tryasharewareprogramandcontinueusingit,youareexpectedto
registerit.Individualprogramsdifferondetailsoftrialperiods,
registration,andpayment.Pleaseobservetherequirementsstatedin
appropriatefiles.
CopyProtection
TheSoftwareinwholeorinpartmayormaynotbecopy-protectedor
encrypted.However,inallcases,resellingorredistributingthesefiles
withoutauthorizationisexpresslyforbiddenexceptasspecifically
providedforbytheOwner(s)therein.
ThisbookisdedicatedtoSisterMarieImelda,C.S.C,whointhelate
1970sfoughtandstruggledtoteachabunchofgoofyhighschoolkids
howtoprogram.Thanks,Sister.“TrustintheLordwithallyourheartand
leannotonyourownunderstanding;inallyourwaysacknowledgehim,
andhewillmakeyourpathsstraight.”Prov.3:5-6(NIV)


Acknowledgments
First,allhonor,glory,andpraisegoestoGod,whothroughHisSon,all
thingsarepossible,andwhogivesusthegiftofeternallife.
IwouldliketothankallthegreatpeopleatSybexfortheirhelp,guidance,
andprofessionalism.ThankstoDeniseSantoroLincoln,theAcquisitions
Editor,forofferingmetheopportunitytowritethisbook.Also,thanksto
CarolHenry,theDevelopmentalEditor,forallherworkguidingthisbook
alongandhelpingmakemyparagraphsmakesense.
ManythankstoSallyEngelfried,theCopyEditor,forturningmypoor
grammarintoperfectsentences,andtoDanFrumin,theTechnicalEditor,
forgoingaboveandbeyondthecallofdutyfixingmyprogramsand
pointingoutmytechnicalblunders.Also,thankstoCaroleMcClendonat
WatersideProductionsforherhelpinarrangingthisbookforme.
Finally,Iwouldliketothankmyparents,MikeandJoyceBlum,fortheir

dedicationandsupport,andmywifeBarbaraanddaughtersKatieJane
andJessicafortheirfaith,love,andunderstanding,especiallywhileIwas
writingthisbook.
Thequotationonthebottomofthefrontcoveristakenfromthesixty-third
chapterofLaoTzu’sTaoTeChing,theclassicworkofTaoistphilosophy.
ThisparticularverseisfromthetranslationbyD.C.Lau(copyright1963)
andcommunicatestheideathatoneshouldconfrontthedifficultwhileit
isstilleasyandaccomplishagreattaskbyaseriesofsmallacts.
ItistraditionallyheldthatLaoTzulivedinthefifthcenturyB.C.inChina,
duringtheChoudynasty,butitisunclearwhetherhewasactuallya
historicalfigure.ItissaidthathewasateacherofConfucius.The
conceptsembodiedintheTaoTeChinginfluencedreligiousthinkingin
theFarEast,includingZenBuddhisminJapan.ManyintheWest,
however,havewronglyunderstoodtheTaoTeChingtobeprimarilya
mysticalwork;infact,muchoftheadviceinthebookisgroundedina
practicalmoralphilosophygoverningpersonalconduct.


Introduction
Networks(andnetworkprogramming)havecomealongwayoverthe
past20years.Intheearlydaysofnetworkcomputing(the’80s),network
programmingwaslefttotheadvancedprogrammer,whotypicallybuilt
applicationsusingtheCprogramminglanguagein(mostly)Unix
environments.Now,networksareeverywhere,fromlargecorporationsto
smallhomeusers.Withsomanycomputersconnectedtogethervia
networks,network-awareapplicationsareanacceptednecessity.
Existingapplicationsmustincorporatenetworkfeaturestostay
competitiveinthemarketplace,andaddingnetworkcommunicationto
applicationsisessential.Networkprogramsareusedforeverythingfrom
children’sgamestoadvancedcorporatedatabasesystems.

NetworkprogramminghasalwaysbeenakeyfeatureoftheMicrosoft
Windowsoperatingsystem.Unfortunately,you’vehadtoknowadvanced
CorC++programmingconceptstoutilizethenetworkprogramming
featuresinWindowsprograms.Now,though,the.NETFramework
languagessimplifythetaskofaddingnetworkfeaturestoyour
applications.The.NETlibrariesprovidemanynetworkclassesthatcan
integratenetworkprogramming.
Asanetworkadministrator,I’vewrittenmanynetworkprogramsusingthe
CandJavalanguagesforbothWindowsandUnixplatforms.Today’s
networkmanagementandsecurityrequirementsmakeitessentialto
communicatewithnetworkdevicesandtrackworkstationsonthe
network.Tryingtoquicklywritecleannetworkcodecanbedifficultwhen
youareworkingwithinthestructureoftheCsocketAPIs(especiallyin
WinSock),andrunningJavaapplicationsisoftenapainfulexperience
duetoslowprocessingspeedsandpoorWindowssupport.
TheC#languagehassolvedmanyofmynetworkprogrammingproblems
byallowingmetoquicklyprototypeanddeploynetworkapplications
usingC#classes.CombiningtheC#Formslibrarytowritethegraphical
codewiththeC#Socketlibrarytowritethenetworkingcodemakes
creatingprofessionalnetworkapplicationssimple.WithC#network
classes,whatusedtotakeadaytowriteoftenonlytakesanhourorless.


WhoShouldReadThisBook
Obviously,ifyouareaC#programmerwhoisinterestedincreating
networkprograms,thisbookisspecificallyintendedtohelpyouout.I’ve
describedeachnetworkC#classindetail,andyou’llfindlotsof
examplestohelpyouimplementtheclassesinyourownwork.Ifyou
haveneverbeforewrittenanetworkprogram,I’veincludeduseful
explanationsoftheconceptsandideasbehindnetworkprogrammingin

general,includingcommontechniquesforpassingdatabetweennetwork
devices.
Youmayalreadybefamiliarwithwritingnetworkprogramsusingother
languages,suchasC,C++,orJava.Inthatcase,you’llbeinterestedin
seeinghoweasyitistodothiswiththeC#language.
IfyouarenewtotheC#language,thefirstchapterdescribesthebasics
ofcreatingandcompilingC#programs.Youmaywanttoskipother
chaptersinthefirstpartofthebook,whichdiscussnetworkprogramming
basics,anddiverightintotheC#-specificnetworkprogrammingclasses.


HowThisBookIsOrganized
Thisbookisorganizedintofourseparatesectionsthatcoveraparticular
aspectofnetworkprogramming.
PartI:NetworkProgrammingBasics
Thefirstfourchaptersareintendedforprogrammersjuststartingoutin
networkprogrammingandlookingforsomebackgroundinformation
abouthownetworkprogrammingworksandthepiecesthatarerequired
fornetworkprogramming.
Chapter1,“TheC#Language,”providessomebasicinformationforthe
readernewtoC#,suchaswhichC#packagetousefordevelopment
workandhowtocompileC#programs.
Chapter2,“IPProgrammingBasics,”demonstrateshownetwork
programminghasevolvedfromtheUnixworldtotheworldofWindows,
viatheWinSockinterface,andhow.NETusestheWinSockinterfaceto
accessnetworkresources.
Chapter3,“C#NetworkProgrammingClasses,”offersaquick
introductiontotheentireC#networklibrariesandshowsthebasic
formatsoftheclasses.
Chapter4,“DNSandC#,”roundsouttheintroductorysectionbyshowing

networknoviceshowDNScanresolvehostaddressesandhowtouse
theC#DNSclasses.
PartII:NetworkLayerProgramming
Thenextgroupofchapterspresentsthecoreofnetworkprogramming
topicsinthebook.Eachofthesechaptersdiscussesamajortopicusing
increatingC#networkprograms.
Chapter5,“Connection-OrientedSockets,”startsthediscussionof
networkprogrammingbyintroducingstreamprogrammingusingTCP.In
additiontothestandardC#Socketclassusedforstreamprogramming,
commonpitfallsarediscussedtohelpyoucreatestreamprogramsthat


willworkonrealnetworks.
Chapter6,“ConnectionlessSockets,”discusseshowtousetheSocket
classtocreateUDPapplications.Inadditiontoshowingyouhowto
createUDPapplications,thischapteralsodiscussespitfallsrelatedto
UDPprogrammingandshowsexamplesofcreatingapplicationsthatwill
withstandtheproblemsinherentinrealnetworks.
Chapter7,“UsingtheC#SocketHelperClasses,”discussestheC#
TcpClient,TcpListener,andUdpClientclasses.Theseare
specialclassesin.NETtohelpprogrammerscreatenetworkprograms
withminimaleffort.Thischapteralsodiscussesthebasicsofsending
differentdatatypesacrossthenetwork.
Chapter8,“AsynchronousSocketProgramming,”discussesthe
techniqueofusingasynchronousprogramming(prevalentinWindows
programs)withinthenetworkprogrammingworld.
Chapter9,“UsingThreads,”presentsinformationforusingmulti-threaded
applicationtechniquesinnetworkprograms.Thistechnologyisoften
usedinserverapplicationsthatmustservicemultipleclientsatthesame
time.

Chapter10,“IPMulticasting,”describeshowtousebroadcastingand
multicastingtosendpacketstomultipleclients,cuttingdownonnetwork
bandwidth.


PartIII:ApplicationLayerProgramming
Examples
Thelastpartofthebookdescribesspecificnetworkapplicationsandhow
toimplementthemusingtheC#networkclasses.
Chapter11,“ICMP,”showshowtouseC#rawsocketstoimplementa
protocol-specificapplication.Thecommonpingandtracerouteprograms
areshownwithintheC#networkprogrammingcontext.
Chapter12,“SNMP,”describeshowtowritenetworkmanagement
applicationsusingC#.SNMPallowsyoutocommunicatewithmany
devicesonthenetworktoretrievenetworkstatistics.Thischaptershows
specificexamplesofreadingavendorMIBsheetandcreatingaC#
applicationtoextracttheMIBdatafromthenetworkdevice.
Chapter13,“SMTP,”describestheC#e-mailclassesandshows
examplesofusingthemtosendmailusingSMTPtoremotemailservers.
Also,anexampleofusingothermailprotocols(suchasPOP3)isshown.
Chapter14,“HTTP,”presentstheC#webclassesandhowyoucanuse
themtocreateweb-enabledC#applications.Also,.NETwebservices,
andhowyoucanusethemtohostyourapplicationmethodsonanIIS
server,arediscussed.
Chapter15,“ActiveDirectory,”showstheC#classesforcontacting
MicrosoftActiveDirectoryservers.Examplesarepresentedthatshow
howtoquery,change,add,anddeleteentriesintheActiveDirectory.
Chapter16,“Remoting,”discussesthe.NETconceptofremoting,
allowinganapplicationtosharemethodswithclientsacrossthenetwork.
Examplesareshownthatdemonstratehowtocreatebotharemoting

serverandclient.
Chapter17,“Security,”closesoutthebookbydescribinghowthe.NET
Frameworkhandlesprogramsecurity,andhowyoucanimplement
securityinyournetworkapplicationsusingencryptiontechniques.


PartII:NetworkLayerProgramming
Thenextgroupofchapterspresentsthecoreofnetworkprogramming
topicsinthebook.Eachofthesechaptersdiscussesamajortopicusing
increatingC#networkprograms.
Chapter5,“Connection-OrientedSockets,”startsthediscussionof
networkprogrammingbyintroducingstreamprogrammingusingTCP.In
additiontothestandardC#Socketclassusedforstreamprogramming,
commonpitfallsarediscussedtohelpyoucreatestreamprogramsthat
willworkonrealnetworks.
Chapter6,“ConnectionlessSockets,”discusseshowtousetheSocket
classtocreateUDPapplications.Inadditiontoshowingyouhowto
createUDPapplications,thischapteralsodiscussespitfallsrelatedto
UDPprogrammingandshowsexamplesofcreatingapplicationsthatwill
withstandtheproblemsinherentinrealnetworks.
Chapter7,“UsingtheC#SocketHelperClasses,”discussestheC#
TcpClient,TcpListener,andUdpClientclasses.Thesearespecialclasses
in.NETtohelpprogrammerscreatenetworkprogramswithminimal
effort.Thischapteralsodiscussesthebasicsofsendingdifferentdata
typesacrossthenetwork.
Chapter8,“AsynchronousSocketProgramming,”discussesthe
techniqueofusingasynchronousprogramming(prevalentinWindows
programs)withinthenetworkprogrammingworld.
Chapter9,“UsingThreads,”presentsinformationforusingmulti-threaded
applicationtechniquesinnetworkprograms.Thistechnologyisoften

usedinserverapplicationsthatmustservicemultipleclientsatthesame
time.
Chapter10,“IPMulticasting,”describeshowtousebroadcastingand
multicastingtosendpacketstomultipleclients,cuttingdownonnetwork
bandwidth.


KeepingUptoDate
Alloftheexamplesinthisbookhavebeencreatedandcompiledusing
the.NETFramework1.0package.Eachoftheexampleswilleasily
compileusinganyoftheMicrosoftVisualStudiopackages(including
VisualC#).
Atthetimeofthiswriting(2002)thecurrentversionofthe.NET
Frameworkwasversion1.0,withServicePack1.Microsoftmaintainsthe
.NETFrameworkwebsiteat
whereall.NET
announcementsareposted.


PartI:NetworkProgrammingBasics


ChapterList
Chapter1:TheC#Language
Chapter2:IPProgrammingBasics
Chapter3:C#NetworkProgrammingClasses
Chapter4:DNSandC#


Chapter1:TheC#Language



Overview
Initsshorthistory,theMicrosoft.NETtechnologyhasquicklybecomea
popularprogrammingplatformfordevelopingapplicationsforMicrosoft
Windowsworkstationsandservers.Althoughmostofthemediaattention
hasfocusedaroundthewebapplicationcapabilitiesof.NET,thereare
manyotherfeaturesthatareusefultoWindowsprogrammers.
OneofthosefeaturesisthenewC#programminglanguage,developed
specificallyfor.NET.C#isbecomingawidelyusedprogramming
platformforprogrammerswantingtocreatebothnetwork-awareand
stand-aloneapplicationsforWindowssystems.Thelanguageprovides
manyresourcestohelpcreaterobustWindows-basedapplications.Many
programmersaremigratingtotheC#languagetotakeadvantageof
theseresources.
BeforelearningthebasicsofnetworkprogramminginC#,itisimportant
thatyouunderstandtheC#programmingenvironment,thefundamentals
of.NET,andhowtocreateanddistributeC#applications.Thischapter
showshowtocreateaC#developmentenvironmentonyoursystemand
howtoensurethatC#applicationsyoucreatewillrunonotherWindows
workstationsandservers.Finally,I’llpresentabriefintroductiontotheC#
language,alongwithsomeC#programmingtopicsrelevanttonetwork
programming.Alltogether,theconceptspresentedinthischapterwill
helpyougetreadyforC#networkprogramming.


Basicsof.NET
The.NETgroupofprogramminglanguagesdiffersfromprevious
versionsofWindowsprogramminglanguagesinthewayprogramsare
createdandrunontheWindowssystems.Ifyouarenotfamiliarwithhow

C#programsoperate,thissectionbrieflydescribesthebasicsyoushould
knowtobeabletodeployapplicationsbasedonthe.NETtechnologies.

CommonLanguageRuntime(CLR)
ThecoreoftheMicrosoft.NETtechnologyistheCommonLanguage
Runtime(CLR)environment.Thisenvironmentenablesprogrammersto
createprogramsusingamultitudeofprogramminglanguagesandrun
themonanyplatformthatsupportstheCLR.TheideaoftheCLRisto
provideamiddlelayerofApplicationProgramInterfaces(APIs)that
operatebetweenthelow-levelWindowsWin32APIfunctionsandthe
applicationprogramcode.Byprovidingacommonmiddlelayer,Microsoft
hasgivenalargernumberofapplicationlanguagesaccesstocore
Windowstechnologies(suchasnetworksupport).
ThelayoutofhowapplicationprogramsrunintheCLRenvironmentis
showninFigure1.1.High-levelapplicationswritteninvarious.NET
languages,suchasVisualBasic.NET,VisualC++.NET,VisualJ#.NET,
andofcourseVisualC#.NET,arecompiledintoaspecialintermediate
languagecalledMicrosoftIntermediateLanguage(MSIL).TheMSILcode
isinterpretedbytheCLRastheprogramruns;MSILrunsonthehost
operatingsystemasanormalexecutableprogram.Ofcourse,legacy
programsthatdonotusetheCLRcanstilldirectlyaccessthelow-level
WindowsWin32APIsasbefore.


Figure1.1:TheCommon
LanguageRuntime(CLR)environment

ThisCLRmodelalsopertainstootheroperatingsystems.Becausethe
CLRisportedtootheroperatingsystems,.NETprogramswillbeableto
runwithoutrecompilingthemonthenewhostsystems.Currently,

MicrosoftsupportstheSharedSourceCommonLanguageInterface(CLI)
project(nicknamedRotor),whichportstheCLRenvironmenttothe
FreeBSDoperatingsystem.ItisexpectedthattheRotorprojectwill
branchouttootheroperatingsystemsaswell.Atthetimeofthiswriting
youcangetmoreinformationaboutRotoratthefollowingwebsite:
/>ForprogramstorunintheCLR,theymustbecompiledintothespecial
MSILformat.The.NETC#compilerisusedtoconvertC#language
programstoMSILcodethatrunsintheCLRenvironment.Thenext
sectiondescribestheMSILcode.

MSILCode
WhenyoucompileaC#program,itproducesanexecutablefile.
However,thisexecutablefileisdifferentfromtheonesyoumaybeused
toseeingproducedfromotherWindowscompilers.Insteadofalow-level
assemblyprogramthatcanrundirectlyinWindows,thisexecutablefile
containstwoparts:
AstubassemblylanguageprogramtostarttheCLRcompiler
TheMSILcodeofthecompiledapplication
ThestubprogramstartstheCLRjust-in-time(JIT)compiler,which


compilestheMSILprogramcodetonativeWin32codethatcanberun
onthesystem.UnlikenativeWindowsapplications,whichinteractdirectly
withthelow-levelWin32APIsystem,.NETapplicationsrelyonthe.NET
FrameworkCLRtorun.Runninga.NETapplicationonasystemthat
doesnothavethe.NETFrameworkinstalledwillproduceanerror
messageliketheoneinFigure1.2.The.NETFrameworkiscrucialto
any.NETapplication,whetheritisrunningonaWindowsworkstationor
server.WithoutittheMSILcodecannotrun.AnyWindowsworkstationor
serverexpectedtorun.NETprogramsmusthavethe.NETFramework

installed.


Figure1.2:Tryingtoruna.NETapplicationwithoutthe.NET
Framework
Microsoftiscommittedtoensuringthe.NETFrameworkwillbeinstalled
onallfutureversionsoftheWindowsOS.However,olderversionsof
Windowsmusthavethe.NETFrameworkmanuallyinstalled.The
followingsectionincludesinstructionsforinstallingthe.NETFramework
foradeveloperenvironmenttoallowyoutocreate,compile,andrun
.NETapplications.


InstallingaC#DevelopmentEnvironment
BeforeyoucanbeginprogramminginC#,youmusthaveaC#
developmentenvironment—asystemforcreating,compiling,and
debuggingC#programs.Unfortunately,oneofthemoststringent
requirementsfor.NETapplicationdevelopmentisthedesignationofOS
platformtousefordevelopment.Currently,.NETrequiresoneofthe
followingsystemsforfullC#programdevelopment:
WindowsNT4WorkstationorServer(withServicePack6a)
Windows2000ProfessionalorServer(withServicePack2)
WindowsXPHomeEditionorProfessional
Programmerswithoutaccesstoanyofthesesystemswillnotbeableto
developC#programs—butthereisasolutiontothis,aswillbeexplained
laterintheC#RuntimeEnvironmentsection.

C#DevelopmentOptions
MicrosoftoffersthreedevelopmentenvironmentsforC#developers.
Eachenvironmenthasitsownsetofprosandcons.Thissection

describestheseC#developmentenvironmentsandhowtheydiffer.
VisualStudio.NET
VisualC#.NET
.NETFrameworksoftwaredevelopmentkit(SDK)
Note Alloftheexampleprogramsinthisbookcanbe
compiledinanyofthe.NETdevelopment
environments.Tosimplifythings,thisbook’sexamples
areshownusingthe.NETFrameworkcommand-line
compiler.Thisensuresthatanyonecanusethe
examples,nomatterwhichdevelopmentenvironment
youareusing.


VisualStudio.NET
TheVisualStudio.NETpackageistheflagshipdevelopmentproductfor
Microsoft.NET.ThisIntegratedDevelopmentEnvironment(IDE)offers
manyfeaturestoassistyourWindowsapplicationprogrammingtasks.
MicrosoftdescribestheVisualStudiopackageas“arapidapplication
development(RAD)tool,enablingprogrammerstoquicklycodeand
debug.NETapplications.”Itincludesacompletegraphicalenvironment
forcreatingWindowsforms,typingcode,anddebuggingprograms.In
additiontocontainingafancydevelopmentenvironment,VisualStudio
alsosupportsallthe.NETprogramminglanguages—VisualBasic.NET,
VisualC++.NET,VisualJ#.NET,andVisualC#.NET.Ifyouarelooking
atdevelopingwithallofthe.NETlanguages,theVisualStudiopackage
iswellworththeextraexpense.
InVisualStudio.NET,applicationscanbecreatedinagraphical
environmentusinganyofthefourprogramminglanguages.TheIDE
providesseparatewindowsfordevelopingcodeandforvisuallylaying
outWindowcontrolsfortheapplication,includingtextboxes,listboxes,

buttons,andscrollbars.VisualStudio.NEToffersaneasywaytocreate,
test,anddebug.NETapplications,whethertheyarestand-alone
WindowsapplicationsorASP.NETwebpages.
ThereareseveralpackagelevelsforVisualStudio.NET,dependingon
yourdevelopmentrequirements(andbudget).Eachpackagelevel
includesprogressivelymoredevelopmentfunctionality,andalsocomes
withaprogressivelyhigherpricetag.

VisualC#.NET
IfyouareinterestedonlyinprogrammingusingtheC#language,youdo
nothavetobuythefullVisualStudio.NETpackage.Instead,Microsoft
offerstheVisualC#.NETpackage,whichhasthesamefunctionalityof
VisualStudio.NETbutsupportsonlytheC#language.Thisisamuch
lessexpensivemethodofdevelopmentforC#programmers.Similarto
VisualStudio,theVisualC#packagealsocomesinvariouspackage
levels,fromabare-bonesstudentversiontoafull-featuredprofessional
developerversion.Beforeyouchoosethisversion,however,beaware


×