tutorial 1-schema

Upload: guru-balan

Post on 08-Aug-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/22/2019 Tutorial 1-Schema

    1/29

    AnIntroductionToInternetProgrammingWithSocketWrench.NET

  • 8/22/2019 Tutorial 1-Schema

    2/29

    AnIntroductionToInternetProgramming Page2

    IntroductionTheTransmissionControlProtocol/InternetProtocol(TCP/IP)isthecommonlanguagespokenbyevery

    deviceandapplicationthatcommunicatesovertheInternet.Asadeveloperwhoisinterestedin

    integratingInternetfunctionalityintoyourownsoftware,itisimportanttounderstandthe

    fundamentalsofhowTCP/IPworks.Thistutorialwillexplainthebasicconceptsbehindnetwork

    programming,andhelpgetyoustarteddevelopingyourfirstInternetapplication.

    TheexamplesincludedinthistutorialaregearedprimarilytowardsVisualBasicdevelopers;however,

    thegeneralconceptscanbeappliedtoany.NETprogramminglanguage.Toworkwiththeseexamples,

    youshouldhaveVisualStudio2005andSocketWrench.NETinstalled.SocketWrenchisthegeneral

    purposeTCP/IPnetworkingcomponentthatweusethroughoutourexamples.

    SocketWrenchisalsopartofalargercollectionofInternetcomponentsinourSocketToolsfamilyof

    products.WithSocketTools,youcaneasilytakeadvantageoffeaturessuchasuploadingand

    downloadingfiles,sendingemailmessages,managingyourInboxonyourmailserver,submittingdata

    toaweb

    server,

    executing

    remote

    commands

    and

    much

    more.

    While

    SocketWrench

    makes

    it

    easy

    to

    createyourowncustomclientandserverapplications,SocketToolsfurthersimplifiesapplication

    developmentbyenablingyoutoincorporatehighlevelInternetfunctionalityinyoursoftwarewithjust

    afewlinesofcode.MoreinformationandafreeevaluationcopyofbothSocketWrenchandSocketTools

    isavailableontheCatalystDevelopmentwebsiteatwww.catalyst.com

    WindowsSocketsAPITheWindowsSocketsspecificationwascreatedbyagroupofcompanies,includingMicrosoft,inan

    efforttostandardizetheTCP/IPsuiteofprotocolsunderWindows.PriortoWindowsSockets,each

    vendor

    developed

    their

    own

    proprietary

    libraries,

    and

    although

    they

    all

    had

    similar

    functionality,

    the

    differencesweresignificantenoughtocauseproblemsforthesoftwaredeveloperswhousedthem.

    Afterchoosingtouseaspecificvendor'slibrary,thedeveloperwaslockedintothatparticular

    implementationbecauseaprogramwrittenagainstonevendor'sproductwouldnotworkwith

    another's.WindowsSocketswasofferedasasolution,leavingdevelopersandtheirendusersfreeto

    chooseanyvendor'sTCP/IPimplementationwiththeassurancethattheproductwouldcontinueto

    work.Today,thereareafewthirdpartyTCP/IPproductsavailablefortheWindowsplatform;however,

    mostsystemsusetheMicrosoftTCP/IPlibrariesthatareincludedaspartofthebaseoperatingsystem

    andithasbecomethestandardnetworkinginterfaceontheWindowsplatform.

    SocketWrenchisacomponentthatusestheWindowsSocketsAPItosimplifythedevelopmentof

    Internetapplications.Itoffersahigherlevelinterface,enablingthedevelopertosetproperties,invoke

    methodsandcreateeventhandlerstorespondtonetworkevents.InprogramminglanguageslikeVisual

    Basic,itprovidesamorenaturalprogramminginterfacethatavoidsmuchoftheerrorpronedrudgery

    commonlyassociatedwithsocketsprogramming.BysimplyreferencingSocketWrenchinyourproject,

    settingsomepropertiesandrespondingtoevents,youcanquicklyandeasilywriteanInternetenabled

    application.However,beforewegetstartedwithSocketWrench,we'llcoverthebasicterminologyand

    conceptsbehindsocketsprogrammingingeneral.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

    http://www.catalyst.com/http://www.catalyst.com/http://www.catalyst.com/
  • 8/22/2019 Tutorial 1-Schema

    3/29

    AnIntroductionToInternetProgramming Page3

    ProtocolStandardsInthecontextofInternetprogramming,aprotocolestablishesthe"rulesoftheroad"thateach

    computermustfollowsothatallofthesystemsinthenetworkcanunderstandthedatabeing

    exchangedbetweenthem.Therearetwogenerallevelsofprotocolsthataretypicallydiscussed.The

    firstconsistsofthenetworkingprotocolsthatgovernhowtwoormorecomputersystemscommunicate

    withoneanother.TwoexamplesoftheselowerlevelnetworkingprotocolswouldbeTCPandUDP,

    whicharediscussedlaterinthistutorial.

    Thesecondtypeofprotocolisonewhichdetermineshowapplicationsexchangeinformationand

    performcertaintasks.AnexampleofthesehigherlevelprotocolswouldbeHTTPandFTP,whichare

    usedtocommunicatewithwebandfileservers.Thesehigherlevelapplicationprotocolsthenusethe

    lowerlevelnetworkingprotocolssuchasTCPtocommunicateovertheInternet.

    MostInternetprotocols,includingtheprotocolsthatwediscussinthistutorial,aredescribedin

    technicaldocumentscalledRequestforComments(RFCs).Thesedocumentsarepublishedthroughthe

    InternetSociety,

    an

    international

    organization

    of

    computer

    scientists

    and

    engineers

    that

    promote

    Internetstandards.EventuallysomeoftheseproposedInternetprotocolsareadoptedbytheInternet

    EngineeringTaskForce(IETF),whichformalizesthemasstandardprotocols.

    Anumberisusedtoreferencethestandardsdocumentforeachprotocol.Forexample,thestandards

    documentfortheFileTransferProtocolisnumber959,andiscommonlyreferredtoasRFC959.Alistof

    theavailableRFCdocumentsisavailableattheIETFwebsite:

    http://www.ietf.org/

    ItsimportanttokeepinmindthatRFCsaretechnicaldocumentsthatdescribetheimplementation

    detailsof

    aparticular

    protocol,

    and

    are

    not

    meant

    to

    provide

    an

    overview

    of

    the

    protocol

    in

    laymans

    termsorexplainhowtouseaparticularprotocol.Forexample,RFC959describeshowFTPis

    implemented,butitwillnotexplainhowtouseanapplicationtodownloadafile.Thelanguageusedin

    RFCsalsotendstobeplatformneutral.Inotherwords,youwonttypicallyfindspecificimplementation

    informationfortheWindowsoperatingsystem.Thosekindsofplatformspecificdetailsarelefttothe

    programmer,andnoassumptionsaremadeabouttheunderlyinghardwareoroperatingsystem.

    TheTransmissionControlProtocolWhentwocomputerswishtoexchangeinformationoveranetwork,thereareseveralcomponentsthat

    must

    be

    in

    place

    before

    the

    data

    can

    actually

    be

    sent

    and

    received.

    Of

    course,

    the

    physical

    hardware

    mustexist,whichistypicallyeitheranetworkinterfacecard(NIC)oraserialcommunicationsportfor

    dialupnetworkingconnections.Inadditiontothephysicalconnection,computersalsoneedtousea

    protocolthatdefinestheparametersofthecommunicationbetweenthem.Oneofthemostpopular

    protocolsinusetodayisTCP/IP,whichstandsforTransmissionControlProtocol/InternetProtocol.

    Byconvention,TCP/IPisusedtorefertoasuiteofprotocols,allbasedontheInternetProtocol(IP).

    Unlikeasinglelocalnetwork,whereeverysystemisdirectlyconnectedtoeachother,aninternetisa

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

    http://www.ietf.org/http://www.ietf.org/http://www.ietf.org/
  • 8/22/2019 Tutorial 1-Schema

    4/29

    AnIntroductionToInternetProgramming Page4

    collectionofnetworks,combinedintoasingle,virtualnetwork.TheInternetProtocolprovidesthe

    meansbywhichanysystemonanynetworkcancommunicatewithanotheraseasilyasiftheywereon

    thesamephysicalnetwork.Eachsystem,commonlyreferredtoasahost,isassignedauniquenumber

    thatcanbeusedtoidentifyitoverthenetwork.ThemostcommonversionoftheInternetProtocolused

    todayisIPv4(version4)whichusesa32bitvaluefortheaddress.Typically,thisaddressisbrokeninto

    four8bit

    numbers

    separated

    by

    periods.

    This

    is

    called

    dot

    notation,

    and

    looks

    something

    like

    "192.43.19.64".Somepartsoftheaddressareusedtoidentifythenetworkthatthesystemisconnected

    to,andtheremainderidentifiesthesystemitself.TherearethreeclassesofInternetaddresses,

    generallyreferredtoasclassA,BandC.TheruleofthumbisthatclassAaddressesareassigned

    toverylargenetworks,classBaddressesareassignedtomediumsizednetworks,andclassC

    addressesareassignedtosmallernetworkswithlessthanapproximately250systems.Itshouldbe

    notedthatthelatestversionoftheInternetProtocolisIPv6(version6),whichsupports128bit

    addresses.However,atthispointIPv4isstillthemostwidelyusedversionoftheprotocolandtheuseof

    IPv6remainslargelylimitedtoresearchandgovernmentalnetworks.Itisgenerallypredictedthatthe

    widespreadadoptionofIPv6willbephasedinoverthenextfivetotenyears.

    WhenasystemsendsdataoverthenetworkusingtheInternetProtocol,itissentindiscreteunitscalled

    datagrams,alsocommonlyreferredtoaspackets.Adatagramconsistsofaheaderfollowedby

    applicationdefineddata.Theheadercontainstheaddressinginformationthatisusedtodeliverthe

    datagramtoitsdestination,muchlikeanenvelopeisusedtoaddressandcontainpostalmail.Andlike

    postalmail,thereisnoguaranteethatadatagramwillactuallyarriveatitsdestination.Infact,

    datagramsmaybelost,duplicatedordeliveredoutoforderduringtheirtravelsoverthenetwork.

    Needlesstosay,thiskindofunreliabilitycancausealotofproblemsforsoftwaredevelopers.Whats

    reallyneededisareliable,straightforwardwaytoexchangedatawithouthavingtoworryaboutlost

    packets

    or

    jumbled

    data.

    Tofillthisneed,theTransmissionControlProtocol(TCP)wasdeveloped.BuiltontopofIP,TCPoffersa

    reliable,fullduplexbytestreamthatmaybereadandwrittentoinafashionsimilartoreadingand

    writingafile.Theadvantagestothisareobvious:theapplicationprogrammerdoesntneedtowrite

    codetohandledroppedoroutoforderdatagrams,andinsteadcanfocusontheapplicationitself.And

    becausethedataispresentedasastreamofbytes,existingcodecanbeeasilyadoptedandmodifiedto

    useTCP.

    BeforetwoprogramscanbegintoexchangedatausingTCP,theymustestablisha"connection"with

    eachother.Thisisdonewithathreewayhandshakeinwhichbothsidesexchangepackets,establishing

    theinitial

    packet

    sequence

    numbers.

    The

    client

    is

    responsible

    for

    initiating

    the

    connection,

    while

    the

    serversresponsibilityistowait,listenandrespondtoincomingconnections.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    5/29

    AnIntroductionToInternetProgramming Page5

    Thefirststepisfortheclienttosendasynchronization(SYN)packettotheserverthatcontainsits

    sequencenumber.Next,theserverrespondswithanacknowledgementandsynchronization(SYNACK)

    packetthat

    contains

    its

    sequence

    number

    in

    response.

    Finally,

    the

    client

    sends

    an

    acknowledgement

    (ACK)backtotheserver.Oncetheconnectionhasbeenestablished,bothsidesmaysendandreceive

    datauntiltheconnectionisclosed.Thisseriesofstepsisimportantbecauseitensuresthatthebytesof

    dataexchangedbetweentheclientandserverwillbereceivedinthesameordertheyweresent.

    TCPisknownasastreamorientedprotocolbecausedataisexchangedbetweentheclientandserveras

    astreamofbytes.WhileTCPwillguaranteethatthedatawillarriveintact,withthebytesreceivedinthe

    sameorderthattheywerewritten,thereisnoguaranteethattheamountofdatareceivedinasingle

    readoperationonthesocketwillmatchtheamountofdatawrittenbytheremotehost.

    Forexample,consideraserverthatsendsdatatoaclientinfourseparateoperations,eachcontaining

    1024bytes

    of

    data.

    While

    it

    is

    convenient

    to

    think

    of

    these

    as

    discrete

    blocks

    of

    data,

    TCP

    considers

    it

    a

    streamof4096bytes.Theclientmayreceivethatdatainasinglereadonthesocket,returningall4096

    bytes.Alternatively,itmayreadthesocket,andonlyreceivethefirst1460bytes;subsequentreadsmay

    returnanother1460bytes,followedbytheremaining1176bytes.Applicationswhichmakeassumptions

    abouttheamountofdatatheycanreadorwriteinasingleoperationmayworkinsomeenvironments,

    suchasonalocalnetwork,butfailonslowerconnections.

    AgeneralruletousewhendesigninganapplicationusingTCPistoconsiderhowtheprogramwould

    handlethesituationwherethereadoperationonlyreturnsasinglebyte.Iftheapplicationcancorrectly

    handlethiskindofextremecase,thenitshouldfunctioncorrectlyevenunderadversenetwork

    conditions.

    Insomesituationsitmaybedesirabletodesigntheapplicationtoexchangeinformationasdiscrete

    messagesorblocksofdata.Whilethisisn'tdirectlysupportedbyTCP,itcanbeimplementedontopof

    thedatastream.Thereareseveralmethodsthatcanbeusedtoaccomplishthis,dependingonthe

    requirementsoftheapplication:

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    6/29

    AnIntroductionToInternetProgramming Page6

    1. Exchangethedataasfixedlengthstructures.Thisisthesimplestapproach,andhasverylittleornooverhead.Theclientandservercaneitherusepredefinedvalues,ornegotiatethesizeofthe

    datastructureswhentheconnectionisestablished.

    2. Prefixvariablelengthdatastructureswiththenumberofbytesbeingsent.Thelengthvaluecould

    be

    expressed

    either

    as

    anative

    integer

    value,

    or

    as

    afixed

    length

    string

    that

    is

    converted

    toanumericvaluebytheapplication.Thisallowsthereceivertoreadthisfixedlengthvalue,

    andthenusethatvaluetodeterminehowmanyadditionalbytesmustbereadtoobtainthe

    completemessageordatastructure.

    3. Prefixthedatawithauniquebyteorbytesequencethatwouldnormallynotbefoundinthedatastream.Thiswouldbefollowedbythedataitself,withacompletemessagereceivedwhen

    anotheruniquebytesequenceisencountered.Alternatively,auniquebytesequencecouldbe

    usedtoterminateamessage.ThisistheapproachthatmanyInternetapplicationprotocolsuse,

    suchasFTP,SMTPandPOP3.Commandsaresentasoneormoreprintablecharacters,

    terminatedwithacarriagereturn(CR)andlinefeed(LF)bytesequencethattellstheremote

    hostthatacompletecommandhasbeenreceived.

    4. Acombinationoftheabovemethods,usinguniquebytesequences.ThemessagelengthandevenadditionalinformationsuchasaCRC32checksumorMD5hashcanbeusedtovalidate

    theintegrityofthedata.Thiswouldeffectivelycreatean"envelope"aroundthedatabeing

    exchanged,andadditionalcheckscouldbemadetoensurethatthedatahasbeenreceivedand

    processedcorrectly.

    Regardlessofthemethodused,forbestperformanceitisrecommendedthattheapplicationbufferthe

    datareceivedandthenprocessthedataoutofthatbuffer.Whenusingasynchronous(nonblocking)

    sockets,the

    application

    should

    read

    all

    of

    the

    data

    available

    on

    the

    socket,

    typically

    in

    aloop

    which

    adds

    thedatatothebufferandexitingtheloopwhenthereisnomoredataavailableatthattime.

    TheUserDatagramProtocolUnlikeTCP,theUserDatagramProtocol(UDP)doesnotpresentdataasastreamofbytes,nordoesit

    requirethatyouestablishaconnectionwithanotherprograminordertoexchangeinformation.Datais

    exchangedindiscreteunitscalleddatagrams,whicharesimilartoIPdatagrams.Infact,theonly

    featuresthatUDPoffersoverrawIPdatagramsareportnumbersandanoptionalchecksum.

    UDPissometimesreferredtoasanunreliableprotocolbecausewhenaprogramsendsaUDPdatagram

    overthenetwork,thereisnowayforittoknowthatitactuallyarrivedatitsdestination.Thismeans

    thatthesenderandreceivermusttypicallyimplementtheirownacknowledgementprotocolontopof

    UDP.MuchoftheworkthatTCPdoestransparently(suchasgeneratingchecksums,acknowledgingthe

    receiptofpackets,retransmittinglostpacketsandsoon)mustbeperformedbytheapplicationitself.

    WiththelimitationsofUDP,youmightwonderwhyitsusedatall.UDPhastheadvantageoverTCPin

    twocriticalareas:speedandpacketoverhead.BecauseTCPisareliableprotocol,itgoesthroughgreat

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    7/29

    AnIntroductionToInternetProgramming Page7

    lengthstoinsuredataarrivesatitsdestinationintact,andasaresult,itexchangesafairlyhighnumber

    ofpacketsoverthenetwork.UDPdoesnthavethisoverheadandisconsiderablyfasterthanTCP.In

    situationswherespeedisparamount,orthenumberofpacketssentoverthenetworkmustbekepttoa

    minimum,UDPisoftenthepreferredsolution.AcommonuseofUDPiswithvideoandaudiostreaming,

    wherethedownsideofpotentialpacketlossisoutweighedbythebenefitsofafastertransferrateand

    reducedbandwidth.

    HostnamesBeforeanapplicationcanexchangedatawithanothercomputersystem,itmusthaveseveralessential

    piecesofinformation.ThefirstistheInternetProtocoladdressoftheremotehost.Thisaddressis

    typicallyexpressedeitherasitsnumericalvalueindotnotation,orbyalogicalnamecalledahostname.

    Likeanaddressindotnotation,hostnamesaredividedintoseveralpiecesseparatedbyperiods,called

    domains.Domainshaveahierarchicalstructure,wherethetopleveldomainsdefinethetypeof

    organizationtowhichthatnetworkbelongs,andsubdomainsfurtheridentifythespecificnetwork.

    Inthis

    figure,

    the

    top

    level

    domains

    are

    "gov"

    (government

    agencies),

    "com"

    (commercial

    organizations),"org"(organizations)and"net"(serviceproviders).Thefullyqualifieddomainnameis

    specifiedbynamingthehostandeachparentsubdomainaboveit,separatingthemwithperiods.For

    example,thefullyqualifieddomainnameforthe"jupiter"hostwouldbe"jupiter.catalyst.com".The

    system"jupiter"ispartofthe"catalyst"domain(acompanyslocalnetwork),whichinturnispartofthe

    "com"topleveldomain(adomainusedbyallcommercialenterprises).

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    8/29

    AnIntroductionToInternetProgramming Page8

    Inordertouseahostnameinsteadofadotaddresstoidentifyaspecificsystemornetwork,theremust

    besomecorrelationbetweenthetwo.Thisisaccomplishedbyoneoftwomeans:alocalhosttableora

    domainnameserver.AhosttableisatextfilethatliststheIPaddressofahost,followedbythenames

    thatitsknownby.Typicallythisfileisnamedhostsandisfoundinthe

    C:\Windows\System32\Drivers\Etcfolder.

    Adomainnameserver,ontheotherhand,isasystemthatcanbepresentedwithahostnameandwill

    returnthathostsIPaddress.Thisapproachisadvantageousbecausethehostinformationfortheentire

    networkismaintainedinonecentralizedlocation,ratherthanbeingscatteredaboutoneveryhoston

    thenetwork.

    ServicePortsInadditiontotheIPaddressoftheremotesystem,anapplicationalsoneedstoknowhowtoaddress

    thespecificprogramwithwhichitwishestocommunicate.Thisisaccomplishedbyspecifyingaservice

    port,

    a

    16

    bit

    number

    that

    uniquely

    identifies

    an

    application

    running

    on

    the

    system.

    Instead

    of

    numbers,

    however,servicenamesareusuallyusedinstead.Likehostnames,servicenamesareusuallymatchedto

    portnumbersthroughalocalfile,commonlycalledservices.Thisfileliststhelogicalservicename,

    followedbytheportnumberandprotocolusedbytheserver.Likethehostsfile,thisfileisalsofoundin

    theC:\Windows\System32\Drivers\Etcfolder.

    AnumberofstandardservicenamesareusedbyInternetbasedapplicationsandthesearereferredto

    aswellknownservices.Theseservicesaredefinedbyastandardsdocumentandincludecommon

    applicationprotocolssuchasFTP,POP3,SMTPandHTTP.

    Rememberthataservicenameorportnumberisawaytoaddressanapplicationrunningonaremote

    host.Because

    aparticular

    service

    name

    is

    used,

    it

    doesnt

    guarantee

    that

    the

    service

    is

    available,

    just

    as

    dialingatelephonenumberdoesntguaranteethatthereissomeoneathometoanswerthecall.

    SocketsTheprevioussectionsdescribedwhatinformationaprogramneedstocommunicateoveraTCP/IP

    network.Thenextstepisfortheprogramtocreatewhatiscalledasocket,acommunicationsendpoint

    thatcanbelikenedtoatelephone.However,creatingasocketbyitselfdoesntletyouexchange

    information,justlikehavingatelephoneinyourhousedoesntmeanthatyoucantalktosomeoneby

    simplytakingitoffthehook.Youneedtoestablishaconnectionwiththeotherprogram,justasyou

    needto

    dial

    atelephone

    number,

    and

    to

    do

    this

    you

    need

    the

    address

    of

    the

    application

    to

    which

    you

    wanttoconnect.Thisaddressconsistsofthreekeyparts:theprotocolfamily,InternetProtocol(IP)

    addressandtheserviceportnumber.

    WevealreadytalkedabouttheIPaddressandserviceport,butwhatstheprotocolfamily?Itsa

    numberwhichisusedtologicallydesignatethegrouptowhichagivenprotocolbelongs.Sincethe

    socketinterfaceisgeneralenoughtobeusedwithseveraldifferentprotocols,theprotocolfamilytells

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    9/29

    AnIntroductionToInternetProgramming Page9

    theunderlyingnetworksoftwarewhichprotocolisbeingusedbythesocket.Inourcase,theInternet

    Protocolfamilywillalwaysbeusedwhencreatingsockets.Withtheprotocolfamily,IPaddressofthe

    systemandtheserviceportnumber,yourereadytoestablishaconnection.

    Client-Server

    Applications

    ProgramswrittentouseTCParedevelopedusingtheclientservermodel.Asmentionedpreviously,

    whentwoprogramswishtouseTCPtoexchangedata,oneoftheprogramsmustassumetheroleofthe

    client,whiletheothermustassumetheroleoftheserver.Theclientapplicationinitiateswhatiscalled

    anactiveopen.Itcreatesasocketandactivelyattemptstoconnecttoaserver.Theserverapplication

    createsasocketandpassivelylistensforincomingconnectionsfromclients,performingwhatiscalleda

    passiveopen.

    Whentheclientinitiatesaconnection,theserverisnotifiedthatsomeprocessisattemptingtoconnect

    withit.Byacceptingtheconnection,theservercompleteswhatiscalledavirtualcircuit,alogical

    communications

    pathway

    between

    the

    two

    programs.

    Its

    important

    to

    note

    that

    the

    act

    of

    accepting

    a

    connectioncreatesanewsocket;theoriginalsocketremainsunchangedsothatitcancontinuetobe

    usedtolistenforadditionalconnections.Whentheservernolongerwishestolistenforconnections,it

    closestheoriginalpassivesocket.

    Toreview,therearefivesignificantstepsthataprogramwhichusesTCPmusttaketoestablishand

    completeaconnection.Theserversidewouldfollowthesesteps:

    1. Createasocket.2. Listenforincomingconnectionsfromclients.3. Accepttheclientconnection,creatinganewsocket.4. Sendandreceiveinformation.5. Closethesocketwhenfinished,terminatingtheconversation.

    Inthecaseoftheclient,thesestepsarefollowed:

    1. Createasocket.2. Specifytheaddressandserviceportoftheserverprogram.3. Establishtheconnectionwiththeserver.4. Sendandreceiveinformation.5. Closethesocketwhenfinished,terminatingtheconversation.

    Onlystepstwoandthreearedifferent,dependingonifitsaclientorserverapplication.Whencreating

    aserverapplication,itisgenerallydesirabletouseamultithreadeddesign.Afteracceptingthe

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    10/29

    AnIntroductionToInternetProgramming Page10

    connection,athreadiscreatedtohandlethesocketI/Oforthatparticularsession.Whenthe

    connectionisclosed,thethreadcaneitherbeterminatedorputtosleepuntilanewclientconnection

    hasbeenaccepted.Thiskindofimplementationhasanumberofadvantages,particularlyonsystems

    withmultipleprocessors.Amultithreadedserverisabletohandlealargernumberofclientconnections

    moreefficiently,andgenerallyitiseasiertoimplementanddebugbecauseeachclientsessionoperates

    independentlyfrom

    the

    others.

    AsynchronousSocketsOneofthefirstissuesyoullencounterwhendevelopingyourInternetapplicationisthedifference

    betweensynchronousandasynchronoussockets.Wheneveryouperformsomeoperationonasocket,it

    maynotbeabletocompleteimmediatelyandreturncontrolbacktoyourprogram.Forexample,

    readingdatafromasocketcannotcompleteuntilsomedatahasbeensentbytheremotehost.Ifthere

    isnodatawaitingtoberead,oneoftwothingscanhappen:themethodcanwaituntilsomedatahas

    beenwrittenonthesocket,oritcanreturnimmediatelywithanerrorthatindicatesthatthereisno

    datato

    be

    read.

    Thefirsttypeofsocketiscalledasynchronousorblockingsocket.Inotherwords,theprogramis

    "blocked"untiltherequestfordatahasbeensatisfied.Whentheremotesystemdoeswritesomedata

    onthesocket,thereadoperationwillcompleteandexecutionoftheprogramwillresume.Thesecond

    typeofsocketiscalledanasynchronousornonblockingsocket,andrequiresthattheapplication

    recognizetheerrorconditionandhandlesthesituationappropriately.

    Programsthatuseasynchronoussocketstypicallyuseoneoftwomethodswhensendingandreceiving

    data.Onemethodistohavetheprogramperiodicallyattempttoreadorwritedatafromthesocket,

    typicallyusingatimer.However,thiscanresultinhigherCPUutilizationandnegativelyimpactthe

    overallperformanceofthesystem.Thepreferredmethodistousewhatiscalledasynchronous

    notification.Thismeansthattheprogramisnotifiedwheneverasocketeventtakesplace,andinturn

    canrespondtothatevent.Forexample,iftheremoteprogramwritessomedatatothesocket,anevent

    isgeneratedsothatprogramknowsitcanreadthedatafromthesocketatthatpoint.

    Bydefault,socketI/Oissynchronousandcontrolisnotreturnedtotheprogramuntiltheblocking

    socketoperationhascompleted.However,thiscanintroducesomeproblemsontheWindowsplatform.

    Whenthesocketblocks,itwilleithercausethecurrentthreadtosleep,oritwillprocessWindows

    messagessenttotheapplication.Thiscaneitherresultintheprogramappearingtobecomenon

    responsiveoritmaybereenteredatadifferentpointwiththeblockedoperationparkedonthe

    program'sstack.

    For

    example,

    consider

    aprogram

    that

    attempts

    to

    read

    some

    data

    from

    the

    socket

    whenabuttonispressed.Becausenodatahasbeenwrittenyet,itblocksandtheprogramgoesintoa

    messageloop.Theuserthenpressesadifferentbutton,whichcausescodetobeexecuted,whichin

    turnattemptstoreaddatafromthesocket,andsoon.

    Toresolvethisissuewithblockingsockets,theWindowsSocketsstandardstatesthattheremayonlybe

    oneoutstandingblockedcallperthreadofexecution.Thismeansthatapplicationsthatarereentered

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    11/29

    AnIntroductionToInternetProgramming Page11

    (asintheexampleabove)willencountererrorswhenevertheytrytotakesomeactionwhileablocking

    functionisalreadyinprogress.Thecreationofbackgroundworkerthreadstoperformblockingsocket

    operationsisacommonapproachtoaddressthisissue.Thisallowsthemainuserinterfacethreadto

    continuetoprocessWindowsmessagesandremainresponsivetotheuser.

    Itshould

    be

    noted

    that

    there

    are

    advantages

    to

    using

    blocking

    sockets.

    In

    most

    cases,

    the

    application

    designandimplementationissimpler,andoverallthroughput(therateatwhichdataissentand

    received)isgenerallyhigherwithblockingsocketsbecauseitdoesnothavetogothroughanevent

    mechanismtonotifytheapplicationofachangeinstatus.

    TheSocketWrenchcomponentfacilitatestheuseofnonblockingsocketsbyfiringeventswhen

    appropriate.Forexample,anOnReadeventisgeneratedwhenevertheremotehostwritesonthe

    socket,whichtellsyourapplicationthatthereisdatawaitingtoberead.

    Insummary,therearethreegeneralapproachesthatcanbetakenwhenbuildinganapplication:

    Useasynchronous(blocking)socket.Inthismode,theprogramwillnotresumeexecutionuntilthesocketoperationhascompleted.Ifmultiplesimultaneousconnectionsmustbeestablished

    bytheapplication,itisrecommendedthatyouuseamultithreadeddesign,whereeachsession

    ismanagedbyitsownworkerthread.

    Useanasynchronous(nonblocking)socket.Thismodeallowsyourapplicationtorespondtoevents.Forexample,whentheremotesystemwritesdatatothesocket,anOnReadeventis

    generatedforthecontrol.Yourapplicationcanrespondbyreadingthedatafromthesocket,

    andperhapssendsomedataback,dependingonthecontextofthedatareceived.

    Useacombinationofblockingandnonblockingsocketoperations.Theabilitytoswitchbetweenblockingandnonblockingmodes"onthefly"providesapowerfulandconvenientway

    toperformsocketoperations.

    Ifyoudecidetouseasynchronoussocketsinyourapplication,itsimportanttokeepinmindthatyou

    mustcheckthereturnvaluefromeveryreadandwriteoperation,sinceitispossibleyoumaynotbe

    abletosendorreceiveallthespecifieddata.

    Developersfrequentlyencounterproblemswhentheywriteaprogramthatassumesagivennumberof

    bytescanalwaysbewrittento,orreadfrom,thesocket.Inmanycases,theprogramworksasexpected

    whendevelopedandtestedonalocalareanetwork,butfailsunpredictablywhentheprogramis

    releasedto

    auser

    that

    has

    aslower

    network

    connection

    (such

    as

    aserial

    dial

    up

    connection

    to

    the

    Internet).Byalwayscheckingthereturnvaluesoftheseoperations,youinsurethatyourprogramwill

    workcorrectly,regardlessofthespeedorconfigurationofthenetwork.

    SecureCommunicationsSecurityandprivacyisaconcernforeveryonewhousestheInternet,andtheabilitytoprovidesecure

    transactionsovertheInternethasbecomeoneofthekeyrequirementsformanybusinessapplications.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    12/29

    AnIntroductionToInternetProgramming Page12

    SocketWrenchhastheabilitytoestablishsecureconnectionswithremoteservers,aswellasfunctionas

    asecureserveritself.Althoughmostofthetechnicalissuessuchasdataencryptionarehandled

    internallybythecontrolandlibrary,ageneralunderstandingofthestandardsecurityprotocolsisuseful

    whendesigningyourownapplications.

    Whenyou

    establish

    aconnection

    to

    aserver

    over

    the

    Internet

    (for

    example,

    aweb

    server),

    the

    data

    that

    youexchangeistypicallyroutedoverdozensofcomputersystemsuntilitreachesitsdestination.Any

    oneofthesesystemsmaymonitorandlogthedatathatitforwards,andthereisnowayforeitherthe

    senderorreceiverofthatdatatoknowifthishasbeendone.ExchanginginformationovertheInternet

    couldbelikenedtotalkingwithsomeoneinapublicrestaurant.Anyonecanchoosetolistentowhat

    you'resaying,andunlesstheyintroducethemselves,youhavenoideawhotheyareorifthey'veeven

    heardwhatyousaid.

    ToensurethatprivateinformationcanbesecurelyexchangedovertheInternet,twobasicrequirements

    mustbemet:theremustbeawaytosendthatinformationsothatonlythesenderandthereceivercan

    understandwhatisbeingexchanged,andtheremustbeawayforthemtodeterminethattheyeachare

    infactwhotheyclaimtobe.Thesolutiontothefirstproblemistouseencryption,whereakeyisused

    toencryptanddecryptthedatausingamathematicalformula.Thesecondproblemisaddressedby

    usingdigitalcertificates.ThesecertificatesareissuedbyaCertificationAuthority(CA),whichisatrusted

    thirdpartyorganizationwhoverifiestheidentityoftheindividualorcompanywhoisissueda

    certificate.Thesetwoconcepts,encryptionanddigitalcertificates,arecombinedtoprovidethemeans

    tosendandreceiveinformationsecurelyovertheInternet.

    TheSecureSocketsLayer(SSL)protocolwasoriginallydevelopedbyNetscape,andisstillthemost

    commonprotocolinusetoday.ThelatestimprovementstoSSLhaveresultedintheTransportLayer

    Security(TLS)protocol,anditisbeginningtoreplaceSSLasthestandardforsecurecommunications

    overthe

    Internet.

    Microsoft

    also

    developed

    aprotocol

    similar

    to

    SSL

    called

    the

    Private

    Communication

    Technology(PCT)protocol;however,itisnotwidelyused.Eachoftheseprotocolsweredesignedto

    provideessentiallythesamething:aprivateexchangeofencrypteddatabetweenthesenderand

    receiver,makingitunreadablebyanintermediatesystem.Usingtherestaurantanalogy,itwouldbeasif

    twopeoplewerespeakinginalanguagethatonlytheycouldunderstand.Althoughsomeonesittingat

    thenexttablecouldlisteninontheconversation,theywouldn'thaveanyideawhatwasactuallybeing

    said.

    Asecureconnection,forexamplebetweenawebbrowserandaserver,beginswithwhatiscalledthe

    handshakephasewheretheclientandserveridentifythemselves.Whentheclientfirstconnectswith

    theserver

    it

    sends

    amessage

    to

    the

    server

    and

    the

    server

    responds

    with

    its

    digital

    certificate,

    along

    with

    itspublickeyandinformationaboutwhattypeofencryptionitwouldliketouse.Next,theclient

    generatesamasterkeyandsendsthiskeytotheserver,whichauthenticatesit.

    Oncetheclientandserverhavecompletedthisexchange,keysaregeneratedwhichareusedtoencrypt

    anddecryptthedatathatisexchanged.Withthehandshakecompleted,asecureconnectionbetween

    theclientandserverisestablished.SocketWrenchhandlesthehandshakephaseofthesecure

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    13/29

    AnIntroductionToInternetProgramming Page13

    connectiontransparentlyanddoesnotrequireanyadditionalprogramming.Ifasecureconnection

    cannotbeestablished,anerrorisreturnedandthenetworkconnectionisclosed.

    Afterthehandshakephasehascompleted,theclientmaychoosetoexaminethedigitalcertificate

    returnedbytheserver.Theinformationcontainedinthecertificateincludesthedateitwasissued,the

    dateit

    expires,

    information

    about

    the

    organization

    who

    issued

    the

    certificate

    (called

    the

    issuer)

    and

    to

    whomthecertificatewasissued(calledthesubjectofthecertificate).Theclientmayalsovalidatethe

    statusofthecertificate,determiningifitwasissuedbyatrustedCertificationAuthorityandwas

    returnedbythesamecompanyorindividualitwasissuedto.

    Theremaybecertaincaseswheretheclientdeterminesthere'saproblemwiththecertificate(for

    example,ifthecertificate'scommonnamedoesnotmatchthedomainnameoftheserver),butchooses

    tocontinuecommunicatingwiththeserver.Notetheconnectionwiththeserverwillstillbesecurein

    thiscase.Inothercases,forexampleifthecertificatehasexpired,theclientmaychoosetoterminate

    theconnectionandwarntheuser.

    DigitalCertificatesWithsecureInternetconnections,digitalcertificatesareusedtoexchangepublickeysfordata

    encryptionandtoprovideidentificationinformation.Thisinformationtypicallyincludestheorganization

    thatwasissuedthecertificate,itsphysicallocationandsoon.Thecertificateitselfisusedtovalidatethe

    publickeyactuallybelongstotheentityitwasissuedto.Thecertificatealsoincludesinformationabout

    theCertificationAuthority(CA)whoissuedthecertificate.

    TheCertificationAuthorityisresponsibleforvalidatingtheinformationprovidedbythatorganization,

    andthendigitallysigningthecertificate,establishingarelationshipbetweenthetwoentities.When

    othersvalidate

    the

    certificate,

    they

    know

    it

    has

    been

    issued

    by

    atrusted

    third

    party.

    Forexample,let'ssaythatacompanywantstoimplementasecuresitesothatpeoplecanorder

    productsonline.Theywouldprovideinformationabouttheircompany(organizationalcontacts,

    financialinformationandsoon)toatrustedthirdpartyorganizationsuchasVerisign.Verisignwould

    thenverifythattheinformationtheyprovidedwascompleteandcorrect,andthenwouldissueasigned

    certificatetothem,whichtheyinstallontheirserver.

    Whenauser(clientsystem)connectstotheirserverandchecksthecertificate,theyseethatitwas

    issuedbyVerisign,atrustedCertificationAuthority.Inessence,theuserissayingthatbecausetheytrust

    Verisign,andVerisigntruststhecompanythecertificatewasissuedto,theywilltrustthecompanyas

    well.

    ToestablishthisrelationshipbetweentheCertificationAuthorityandtheorganizationthecertificateis

    issuedto,thereneedstobearootcertificatewhichhasbeensignedbythesametrustedorganization.

    Thisservesasthebeginningofthecertificationpaththatisusedtovalidatesignedcertificates.Using

    theaboveexample,ontheuser'ssystemthereisarootcertificateforVerisign,signedbyVerisign.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    14/29

    AnIntroductionToInternetProgramming Page14

    Rootcertificatesaremaintainedinthelocalsystem'scertificatestorewhichisessentiallyadatabaseof

    digitalcertificates.Thisdatabaseisstructuredsothatdifferenttypesofcertificatescanbeorganizedin

    onecentrallocationonthesystem,andastandardinterfaceisprovidedtoenumerateandvalidate

    thesecertificates.Certificatesareassociatedwithastorename,allowingthemtobeeasilycategorized.

    Forexample,rootcertificatesarestoredunderthename"Root",whileauser'spersonalcertificates

    (alongwith

    their

    private

    keys)

    are

    stored

    under

    the

    name

    "My".

    WhentheWindowsoperatingsystemisinstalled,thereisacertificatestorethatcontainstheroot

    certificatesforthemajorCertificationAuthorities.However,therearesituationswhereadditional

    certificatesmayneedtobeaddedtothesystem.Tofacilitatethis,thesystemmanagementconsolecan

    beusedtoinstallcertificates,aswellasexportorremovecertificatesfromthecertificatestore.When

    managingyoursystem'scertificatestore,youshouldexercisethesamecautionaswhenyoumake

    changestothesystemregistry.Inadvertentlyremovingacertificatecouldresultinerrorswhen

    attemptingtoaccesssecuresystems.

    Ingeneral,

    the

    one

    situation

    where

    certificate

    management

    becomes

    important

    is

    when

    you

    want

    to

    developyourownsecureserver.Thisisbecauseyourserverneedstohaveasignedcertificatetosendto

    theclientinordertoestablishthesecureconnection.Forgeneralpurposecommercialapplications,this

    generallymeansyouwouldneedtoobtainacertificatesignedbyaCertificationAuthoritysuchas

    Verisign.Thiscertificatewouldthenbeinstalledinthecertificatestoreontheserver.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    15/29

    AnIntroductionToInternetProgramming Page15

    Fordevelopmentandtestingpurposesitmaybeinconvenienttopurchaseacertificate.Therealsomay

    besituationsinwhichanorganizationwishestofunctionasitsownCertificationAuthorityandissue

    certificatesthemselves.Thisallowstheorganizationtocontrolhowcertificatesaremanagedandcanbe

    idealforsecureapplicationsthataredesignedforthecorporateintranet.SocketWrenchincludes

    CreatCert,autilitythatenablesyoutocreateyourownselfsignedrootcertificatesandserver

    certificates.For

    more

    information,

    refer

    to

    the

    documentation

    included

    with

    SocketWrench.

    WebClientExampleTogetstartedworkingwithSocketWrench,wellcreateasimpleVisualBasicapplicationthatconnects

    toawebserverandretrievesthecontentsofanHTMLpageonthatserver.Forthisexample,youllneed

    MicrosoftVisualStudio2005,SocketWrench.NETandaworkingInternetconnection.

    ThefirststepafterstartingVisualStudioistocreateanewVisualBasicproject.SelectFile|New|

    Projectfromthemenu,thenselectVisualBasicastheprojecttypeandWindowsApplicationasthe

    project

    template.

    A

    new

    project

    will

    be

    created

    with

    a

    single,

    empty

    form.

    Aftertheprojecthasbeencreated,thenextstepistoaddSocketWrench.NETtoyournewproject.

    SelectProject|AddReferencefromthemenuandadialogwillbedisplayedwhichliststheavailablecomponents.ScrolldowntowhereSocketTools.SocketWrenchisdisplayed,selectitandthenclickon

    theOKbutton.

    TheUserInterface

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    16/29

    AnIntroductionToInternetProgramming Page16

    AftertheSocketWrenchcomponenthasbeenreferencedinyourproject,thenextstepistocreatethe

    Inthisexample,thelargeTextBoxcontrolinthecenteroftheformhastheMultilin

    userinterface.WelladdseveralLabelandTextBoxcontrols,andaButtoncontrol.

    epropertysetto

    True,theWordWrappropertyissettoFalse,andtheScrollBarspropertyissettoBoth.Thiswillenable

    ts.

    t

    number,atimeoutperiodinseconds,andthedocumentthatyouwishtoview.ClickingtheOKbutton

    examplecomplete,thenextstepistowritethecodethatwill

    retrievethedocumentfromtheserver.Todothis,selectView|Codefromthemenu,andaneditorwill

    ch

    ThefirststepiscreatinganinstanceoftheSocketWrenchcomponentandtheninitializingthatinstance.

    ch,wellcreateaprivatemembervariableintheformsclassthat

    I mpor t s Socket Tool s. Socket Wr ench

    ustoviewthecompletedocumentthatsretrievedfromthewebserverandscrollthroughtheconten

    Wehave

    also

    initialized

    the

    TextBox

    controls

    with

    default

    values

    that

    well

    use

    with

    this

    example.

    Whentheapplicationiscompleted,youwillbeabletospecifythenameofthewebserver,thepor

    willestablishaconnectionwiththeserver,requestthedocumentandthenretrievethecontentsofthe

    documentthattheserverreturns.

    Withtheuserinterfaceportionofthe

    displaytheemptyformclass.

    InitializingSocketWren

    TocreateaninstanceofSocketWren

    referencesthecomponent,andnameitasSocket:

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    17/29

    AnIntroductionToInternetProgramming Page17

    Publ i c Cl ass For m1ol s. Socket Wr ench

    d Cl ass

    toinitializethatinstanceofthecomponentwhentheformiscreated.Thisisdoneby

    theInitialize

    method,

    and

    it

    should

    be

    the

    first

    method

    that

    you

    call.

    SocketWrench

    uses

    explicit

    x. Show( "Unabl e t o i ni t i al i ze Socket Wr ench component " )End

    lizemethodfails,itwillreturnavalueofFalse.Inthatcase,wellsimplydisplayanerror

    andterminatetheprogram.Failurecanindicatethattherewasaproblemloadingthe

    solves

    tanceofSocketWrenchisnolongerbeingused. Becausesocketsarealimitedsystem

    Me. For mCl osed

    d Sub

    lizemethodistypicallyinvokedimmediatelybeforetheapplicationterminates.Itwillclose

    activenetworkconnectioncreatedbythatinstanceofSocketWrench,andwillreleaseallofthe

    Pr i vat e Socket As New Socket ToEn

    Next,weneed

    callinginitializationlikethisbecauseitdynamicallyloadsthenetworkinglibrariesthatitrequires.Inturn,this

    allowsyourapplicationtohandleerrorconditionsgracefullyiftheinitializationprocessfailsforsome

    reason.AgoodplacetocalltheInitializemethodisintheformsLoadevent,sowellcreateanevent

    handlerthatdoesthis:

    Pr i vat e Sub For m1_Load( ByVal sender As Obj ect , ByVal e As Syst em. Event Ar gs)Handl es Me. Load

    I f Not Socket . I ni t i al i ze( ) ThenMessageBo

    End I f

    End Sub

    IftheInitia

    message

    networkingsubsystem,oraninternalproblemwiththeSocketWrenchcomponentorhowitwas

    installed.Ifyoucontinuetoencounterthiserror,tryreinstallingSocketWrenchandseeifthatre

    theproblem.

    Foreach

    call

    to

    the

    Initialize

    method,

    there

    should

    be

    acorresponding

    call

    to

    the

    Uninitialize

    method

    whenthatins

    resource,itsagoodideatoexplicitlyreleasethemwhentheyrenolongerneeded.Althoughthe.NET

    garbagecollectorwilleventuallydothisforyou,itsrecommendedthatyoudothisexplicitly.Agood

    placetocalltheUninitializemethodisintheFormClosedevent:

    Pr i vat e Sub For m1_For mCl osed( ByVal sender As Obj ect , ByVal e AsSyst em. Wi ndows. For ms. For mCl osedEvent Ar gs) Handl es

    Socket . Uni ni t i al i ze( )

    En

    TheUninitia

    any

    systemresourcesthatwereallocatedforit.Oncethisisdone,thatinstanceofthecomponentcanno

    longerbeused.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    18/29

    AnIntroductionToInternetProgramming Page18

    EstablishingaConnection

    AfteraninstanceoftheSocketWrenchcomponenthasbeencreatedandinitialized,thenextstepisto

    server.WelldothisintheClickeventhandlerforourButton

    .

    thod

    ,soitsrecommendedthatyoureviewthetechnicalreferencefor

    moreinformation.Inthisexample,wellusetheservername,portnumberandtimeoutvaluetheuser

    t t on1. Cl i ck

    er

    di spl ay.

    alizeafewpropertiestothevaluesprovidedbytheuser.TheHostNamepropertyspecifies

    meorIPaddressoftheserverthatwewanttoconnectto.TheRemotePortproperty

    specifiestheportnumberthatwillbeusedtoestablishtheconnection.TheTimeoutpropertyspecifies

    rorhasoccurred.Inthatcase,we

    displayamessageboxwithadescriptionofthelasterrorusingtheLastErrorStringproperty.Thereis

    rthat

    meaningfulifthepreviousmethodindicatesanerrorhasactuallyoccurred,eitherby

    returningavaluethatindicatesfailureorthrowinganexception.Thismeansyoushouldnevercheckthe

    establishaconnectionwiththeweb

    controlthatwasplacedontheform

    Toconnect

    to

    the

    server,

    well

    use

    the

    Connect

    method.

    Its

    important

    to

    note

    that

    the

    Connect

    me

    canbecalledinseveraldifferentways

    provides.TheTextBox1controlspecifiestheservernameorIPaddress,theTextBox2controlspecifies

    theportnumber,andtheTextBox3controlspecifiesthetimeoutperiodinseconds.Hereswhatour

    Clickeventhandlerlookslikesofar:

    Pr i vat e Sub But t on1_Cl i ck( ByVal sender As Obj ect , ByVal e AsSyst em. Event Ar gs) Handl es Bu

    ' I ni t i al i ze t he Socket Wr ench pr oper t i es, set t i ng t he ser v ' host name, r emot e por t number and t i meout per i od.

    Socket . Host Name = Text Box1. TextSocket . Remot ePor t = I nt eger . Par se(TextBox2. Text )Socket . Ti meout = I nt eger . Par se(TextBox3. Text )

    ' Est abl i sh a connect i on wi t h t he web server , andai l s ' an er r or message i f t he connect i on at t empt f

    I f Not Socket . Connect ( ) Then

    MessageBox. Show( Socket . Last Er r orSt r i ng)Exi t Sub

    End I f

    End Sub

    First,weiniti

    ehostnath

    thenumberofsecondstowaitfortheconnectiontobeestablished.

    Next,wecalltheConnectmethodandcheckthereturnvalue.IfthemethodreturnsTrue,the

    connectionhasbeenestablishedsuccessfully.IfitreturnsFalse,aner

    alsoaproperty

    named

    LastError

    which

    returns

    anumeric

    error

    code

    that

    identifies

    the

    last

    erro

    hasoccurred.

    OneimportantthingtokeepinmindusingtheLastErrorandLastErrorStringpropertiesisthattheir

    valuesareonly

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    19/29

    AnIntroductionToInternetProgramming Page19

    valueoftheLastErrorpropertytodetermineifthepreviousmethodhasfailed;instead,youshould

    alwayscheckthemethodsreturnvalue.

    RequestingtheDocument

    lished,thenextstepistorequestthedocumentfromtheweb

    we

    erto

    Pr i vat e Sub But t on1_Cl i ck( ByVal sender As Obj ect , ByVal e As

    i es, set t i ng t he ser ver

    ( TextBox2. Text )

    nd di spl ay

    t Er r or St r i ng)

    he GET command to t he ser ver usi ng t he Wr i t eLi ne

    i ed.

    TheTextBox4controlspecifiesthenameofthedocumentwewanttoretrievefromtheserver. Ifwe

    be

    Oncetheconnectionhasbeenestab

    server.To

    do

    this,

    well

    send

    the

    GET

    command

    to

    the

    server,

    along

    with

    the

    name

    of

    the

    document

    wouldliketoview.Tosendthiscommand,wellusetheWriteLinemethodwhichsendsalineoftextto

    theremotehost,terminatingitwithacarriagereturnandlinefeedcharactersequence.Thisisvery

    similartohowalineoftextiswrittentoatextfile.HeresourupdatedcodeintheClickeventhandl

    sendtherequesttotheserver:

    Syst em. Event Ar gs) Handl es But t on1. Cl i ck

    ' I ni t i al i ze the Socket Wr ench pr oper t' host name, r emot e por t number and t i meout per i od.

    Socket . Host Name = Text Box1. TextSocket . Remot ePor t = I nt eger . Par seSocket . Ti meout = I nt eger . Par se(TextBox3. Text )

    ' Est abl i sh a connect i on wi t h t he web ser ver , a' an er r or message i f t he connect i on at t empt f ai l s.

    I f Not Socket . Connect ( ) ThenMessageBox. Show( Socket . Las

    Exi t SubEnd I f

    ' Send t

    ' method, r equest i ng the document t hat t he user has speci fI f Not Socket . Wr i t eLi ne( "GET " + TextBox4. Text ) Then

    MessageBox. Show( Socket . Last Err orSt r i ng)Socket . Di sconnect ( )Exi t Sub

    End I f

    d SubEn

    use/asthedocumentname,ittellstheserverwewantthedefaultindexpage.TheGETcommandis

    combinedwith

    the

    name

    of

    the

    document

    and

    sent

    to

    the

    server

    using

    the

    WriteLine

    method.

    It

    is

    importanttonotethisisthesimplestformoftheGETcommand,andisusedfordemonstration

    purposesherebecauseofitssimplicity.ForanexampleofhowamorecomplexGETrequestcan

    performed,refertotheViewPageexampleincludedwithSocketWrench.NET.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    20/29

    AnIntroductionToInternetProgramming Page20

    IftheWriteLinemethodreturnsTrue,thenthatindicatesthecommandhasbeensentsuccessfullyto

    theserver.IfitreturnsFalse,thentheoperationhasfailedandamessageboxisdisplayedtotheuser.If

    thatoccurs,wealsoterminatetheconnectiontotheserverbycallingtheDisconnectmethod.

    ItsimportanttonotethatWriteLineisnottheonlywaythatyoucansenddatatoaserver.For

    example,SocketWrench

    also

    provides

    amore

    general

    purpose

    Write

    method

    which

    can

    be

    used

    to

    send

    datastoredinabytearray,andcanbeusedwhenbinary(nontextual)datamustbeexchangedwiththe

    server.TheresalsothehigherlevelWriteStreammethodwhichcanbeusedtosendverylargeamounts

    ofdatainasinglemethodcall.Formoreinformation,refertotheTechnicalReferencethatisincluded

    withSocketWrench.

    ReadingtheDocument

    Afterthecommandrequestingthedocumenthasbeensent,thenextstepistoreadthecontentsofthe

    documentreturnedbytheserver.ThisisdoneusingtheReadLinemethod,whichreadsalineoftext

    fromtheserverandreturnsitinastring.WecalltheReadLinemethodinaloop,readingeachlineof

    text

    returned

    by

    the

    server,

    until

    there

    is

    no

    more

    data

    available

    to

    be

    read.

    Here

    is

    the

    complete

    code

    fortheClickeventhandler:

    Pr i vat e Sub But t on1_Cl i ck( ByVal sender As Obj ect , ByVal e AsSyst em. Event Ar gs) Handl es But t on1. Cl i ck

    ' I ni t i al i ze t he Socket Wr ench pr oper t i es, set t i ng t he ser ver' host name, r emot e por t number and t i meout per i od.

    Socket . Host Name = Text Box1. TextSocket . Remot ePor t = I nt eger . Par se(TextBox2. Text )Socket . Ti meout = I nt eger . Par se(TextBox3. Text )

    ' Est abl i sh a connect i on wi t h the web ser ver , and di spl ay' an er r or message i f t he connect i on at t empt f ai l s.

    I f Not Socket . Connect ( ) ThenMessageBox. Show( Socket . Last Er r orSt r i ng)Exi t Sub

    End I f

    ' Send t he GET command t o t he ser ver usi ng t he Wr i t eLi ne' method, r equest i ng t he document t hat t he user has speci f i ed.

    I f Not Socket . Wr i t eLi ne( "GET " + TextBox4. Text ) ThenMessageBox. Show( Socket . Last Er r orSt r i ng)Socket . Di sconnect ( )

    Exi t SubEnd I f

    ' Decl ar e t he st r i ng buf f er t hat wi l l cont ai n t he t ext' r et ur ned by the server , and a Bool ean var i abl e.

    Di m str Buf f er As St r i ng = St r i ng. Empt yDi m bCont i nue As Bool ean =Tr ue

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    21/29

    AnIntroductionToInternetProgramming Page21

    ' Cal l t he ReadLi ne met hod i n a l oop unt i l i t r et ur ns a' val ue of Fal se. For each l i ne of t ext t hat i s r ead,' append i t t o t he mul t i l i ne TextBox cont r ol .

    DobCont i nue = Socket . ReadLi ne( st r Buf f er )I f bCont i nue Then

    Text Box5. AppendText ( st r Buf f er + vbCr Lf )End I f

    Loop Unt i l bCont i nue = Fal se

    ' Di sconnect f r om t he ser ver , r el easei ng t he socket handl e' t hat was al l ocat ed f or t hi s sessi on.

    Socket . Di sconnect ( )

    End Sub

    Whenthereisnomoredataavailabletoberead,theReadLinemethodwillreturnFalse,andtheloop

    will

    be

    exited.

    At

    that

    point,

    the

    only

    remaining

    step

    is

    to

    terminate

    the

    connection

    by

    calling

    the

    Disconnectmethod.Thisgracefullyclosestheconnectionandreleasesthesockethandlethatwas

    allocatedfortheconnection.

    Keepinmindthatthereisalsomorethanonewayyoucanreaddatafromtheserver.Whilethe

    ReadLinemethodisdesignedtoreadlinesoftext,thereisalsoageneralpurposeReadmethodthatcan

    beusedtoreceivebinary(nontextual)dataandstoreitinabytearray.Theresalsothehigherlevel

    ReadStreammethodwhichcanreceiveanarbitrarilylargeamountofdatainasinglemethodcalland

    returnitinabufferthatyouprovide.Formoreinformationaboutthesemethods,pleasereviewthe

    TechnicalReferenceincludedwithSocketWrench.

    Nowthat

    we

    have

    completed

    the

    code

    for

    the

    Button

    controls

    Click

    event,

    the

    final

    step

    is

    to

    run

    the

    example.PressingF5willexecutetheprogram,andclickingtheOKbuttonwillretrievetheindexpage

    fromtheCatalystDevelopmentwebserver.Althoughthiswasaverysimpleexample,itdemonstrated

    theimportantaspectsofcreatinganInternetapplicationusingSocketWrench:

    1. UsingtheInitializemethodaftercreatinganinstanceofthecomponent.Thisshouldbedoneshortlyafterthenewinstanceiscreated,andbeforeanyothermethodsare

    invoked.

    2. UsingtheConnectmethodtoestablishaconnectionusingaspecifichostnameandportnumber.ThereturnvaluefromtheConnectmethodwilltellyouiftheconnectionwas

    successful,or

    ifan

    error

    has

    occurred.

    3. SendingdatatotheserverusingtheWriteLinemethod,andreceivingdatafromtheserverusingtheReadLinemethod.Thereturnvaluewillindicateifthemethodwas

    successful,iftherewasanerrororthereisnomoredataavailabletoread.

    4. TerminatingtheconnectionbycallingtheDisconnectmethod.Thismethodshouldbeinvokedwhenthesessionhascompleted,releasingthesockethandlethatwasallocated

    bythepreviouscalltotheConnectmethod.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    22/29

    AnIntroductionToInternetProgramming Page22

    ThesestepsarecommontovirtuallyeveryapplicationyoullcreatewithSocketWrench,andaresimilar

    tothestepsdiscussedintheprevioussectionaboutclientserverapplications.

    CreatingaSecureConnection

    Tocompleteourexample,wellmakeafewmodificationstoalsosupportsecureconnectionstotheweb

    serverusing

    the

    standard

    SSL

    and

    TLS

    protocols.

    One

    of

    the

    benefits

    of

    SocketWrench

    is

    that

    this

    is

    a

    simplechange,typicallyrequiringthatyousetandcheckthevalueofafewproperties.Theinitialclient

    serverhandshake,certificatevalidationandthedataencryptionanddecryptionareallhandledforyou

    automatically.

    AccordingtotheHypertextTransferProtocol(HTTP),thestandardprotocolforwebservers,thedefault

    portnumberforstandard(nonsecure)connectionsisport80.ForsecureconnectionsusingSSL/TLS,the

    defaultportnumberis443.Toaccommodatethis,wellmodifytheexampletocheckiftheuserhas

    specifiedport443,andiftheyhave,establishasecureconnectiontotheserver.Aftersettingthe

    HostName,RemotePortandTimeoutproperties,addthiscode:

    ' I f t he user has speci f i ed por t 443, t hen t hi s shoul d be a' secur e connect i on t o t he web server

    I f Socket . Remot ePor t = 443 ThenSocket . Secur e =Tr ue

    End I f

    TheSecurepropertytellsSocketWrenchthatyouwishtoestablishasecureconnectionwiththeremote

    host.Inmostcases,thisisallyouwillhavetodotoenablethesecurityfeaturesinyourapplication.

    SocketWrenchwillautomaticallyselecttheappropriatesecurityprotocolforyou,checkthecertificate

    returnedbytheremotehostandnegotiateforthestrongestencryptionalgorithmsupportedbyboth

    theclientandserver.

    Onceasecureconnectionhasbeenestablished,anumberofothersecurityrelatedpropertiesbecome

    availabletothecontrol.Thesepropertiesfallintotwogeneralgroups,returninginformationeither

    aboutthesecureconnectionitself,orabouttheserver'sdigitalcertificate.Thepropertieswhichprovide

    informationabouttheconnectionare:

    CipherStrength Thispropertyreturnsinformationabouttherelativestrengthoftheencryption

    thatisbeingusedtosecurethedata.Thevaluereturnedisactuallythelength

    ofthekey(inbits)usedbytheencryptionalgorithm,andwilltypicallybe40,56

    or128.

    A

    key

    length

    of

    40

    bits

    is

    considered

    weak,

    while

    akey

    length

    of

    56

    bits

    isconsideredtobemoderateand128bitorhigherkeysareconsideredvery

    secure.

    HashStrength Thispropertyreturnsinformationaboutthestrengthofthemessagedigest

    (hash)thatwasselected.Commonvaluesreturnedbythispropertyare128and

    160.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    23/29

    AnIntroductionToInternetProgramming Page23

    SecureCipher Thispropertyidentifiestheencryptionalgorithmthatwasselected.The

    algorithmssupportedareRC2,RC4,DES,andTripleDES.Themostcommonly

    usedalgorithmsareAESandRC4.

    SecureHash Thispropertyidentifiesthemessagedigest(hash)algorithmthatwasselected.

    Thealgorithms

    supported

    are

    SHA

    and

    MD5.

    The

    most

    commonly

    used

    messagedigestisMD5.Thisalgorithmisusedduringthehandshakephase

    betweentheclientandserver,andismadeavailabletotheclientfor

    informationalpurposes.

    SecureKeyExchange Thispropertyidentifiesthekeyexchangealgorithmthatwasselected.ThealgorithmssupportedareRSA,KEAandDiffieHellman.Themostcommonly

    usedkeyexchangealgorithmisRSA.

    SecureProtocol Thispropertyidentifiestheprotocolusedtoestablishthesecureconnection.

    TheprotocolssupportedareSSL2.0,SSL3.0,PCT1.0andTLS1.0.

    Inadditiontoinformationaboutthesecureconnection,thereareseveralpropertieswhichreturn

    informationabouttheremoteserver'sdigitalcertificate.Thesepropertiesare:

    CertificateExpires Thispropertyreturnsthedatetheserver'scertificateexpires.Ifthisvalueis

    earlierthanthecurrentdate,thecertificatehasexpired.Inthatcase,itis

    recommendedthatyoualerttheuserthatthecertificateisnolongervalid.

    CertificateIssued Thispropertyreturnsthedatetheserver'scertificatewasissuedbythe

    certificateauthority.Ifthisdateislaterthanthecurrentdate,orlaterthanthe

    datethecertificatewasissued,thecertificateisinvalid.

    CertificateIssuer Thispropertyreturnsinformationabouttheorganizationthatissuedthe

    certificate.Thedataisreturnedasastringwhichcontainsoneormoretagged

    nameandvaluepairs.

    CertificateStatus Thispropertyreturnsinformationaboutthestatusofthecertificate.Theclient

    isresponsibleforcheckingthisvalue,andbasedonthevaluereturned,decide

    iftheconnectionshouldbeterminatedornot.

    CertificateSubject Thispropertyreturnsinformationabouttheorganizationtowhichthecertificatewasissued.LiketheCertificateIssuerproperty,thisproperty

    returnsastring

    which

    contains

    one

    or

    more

    tagged

    name

    and

    value

    pairs.

    ItisrecommendedyourapplicationimmediatelycheckthevalueoftheCertificateStatuspropertyafter

    thesecureconnectionhasbeenestablished.Thisallowsyourapplicationtomakethedecisionasto

    whetherornotitissafetocommunicatewiththeserverbasedonthestatusofthedigitalcertificateit

    returns.Forexample,usingtheabovecodetheCertificateStatuspropertywouldreturnavalueof

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    24/29

    AnIntroductionToInternetProgramming Page24

    SecurityCertificate.certificateValid,whichindicatesthecertificateisvalid. AfterthecalltotheConnect

    method,addthiscode:

    ' I f t hi s i s a secur e connect i on, t hen check t he st at us' of t he ser ver ' s cert i f i cat e. I f t he cer t i f i cat e i s not' val i d, war n t he user and t er mi nat e the connect i on.

    I f Socket . Secur e And _Socket . Cer t i f i cat eSt at us Secur i t yCer t i f i cat e. cer t i f i cat eVal i d ThenMessageBox. Show( "Ther e i s a pr obl em wi t h t he si t e cer t i f i cat e")Socket . Di sconnect ( )Exi t Sub

    End I f

    Althoughthisexampleterminatestheconnectionifthecertificatecannotbevalidated,keepinmindthis

    isnotrequired.Forexample,youcouldmodifytheprogramtodisplayamessageboxindicatingthereis

    aproblemwiththecertificateandaskingiftheywanttocontinue.Evenifthecertificatecannotbe

    validated,the

    connection

    is

    still

    encrypted.

    However,

    an

    invalid

    certificate

    can

    indicate

    the

    site

    has

    been

    compromised,soitisalwaysrecommendedyoustronglyadviseyourusersofthepotentialrisks.

    Ifyouwantedtodisplayspecificinformationaboutacertificate,forexample,thenameofthe

    organizationthatissuedthecertificateorthenameofthecompanythatitwasissuedto,youwould

    needtousetheCertificateIssuerandCertificateSubjectproperties.Thesearestringpropertiesthat

    returnoneormorecommaseparatedvalues.Eachvalueprovidesinformationaboutthecertificate.For

    example,iftheCertificateSubjectpropertyreturnsthisstring:

    C=US, O="RSA Dat a Secur i t y, I nc. "

    Thatwould

    specify

    two

    pieces

    of

    information

    that

    are

    available

    for

    this

    certificate:

    1. C=US2. O="RSADataSecurity,Inc."

    EachofthesevaluesconsistsofanidentifiercalledanRDN(RelativeDistinguishedName)anditsdata.

    Sincethesecondvaluecontainsacomma,itisenclosedinquotes,andthisneedstobeaccountedfor

    whenparsingthestring.ThereareapredefinedsetofRDNsdefinedbytheX.500standardwhichare

    usedincertificates.ThemostcommonlyusedRDNsinX.509certificatesare:

    RDN DescriptionC

    TheISO

    standard

    two

    character

    country

    code.

    S Thenameofthestateorprovince.

    L Thenameofthecityorlocality.

    O Thenameofthecompanyororganization.

    OU Thenameofthedepartmentororganizationalunit.

    CN Thecommonname;withX.509certificates,thisisthedomainnameofthe

    sitethecertificatewasissuedto.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    25/29

    AnIntroductionToInternetProgramming Page25

    So,forexample,ifyouwantedtodeterminethedomainnamethatacertificatewasissuedto,you

    wouldneedtoreadthevalueoftheCertificateSubjectpropertyandparsetheresultingstringforthe

    "CN"(CommonName)RDN.

    Withthechangeswevemadetotheexampletosupportsecureconnections,hereswhatourcomplete

    ButtonClickeventhandlerlookslike:

    Pr i vat e Sub But t on1_Cl i ck( ByVal sender As Obj ect , ByVal e AsSyst em. Event Ar gs) Handl es But t on1. Cl i ck

    ' I ni t i al i ze t he Socket Wr ench pr oper t i es, set t i ng t he ser ver' host name, r emot e por t number and t i meout per i od.

    Socket . Host Name = Text Box1. TextSocket . Remot ePor t = I nt eger . Par se(TextBox2. Text )Socket . Ti meout = I nt eger . Par se(TextBox3. Text )

    ' I f t he user has speci f i ed por t 443, t hen t hi s shoul d be a' secur e connect i on t o t he web ser ver

    I f Socket . Remot ePor t = 443 ThenSocket . Secur e =Tr ue

    End I f

    ' Est abl i sh a connect i on wi t h the web ser ver , and di spl ay' an er r or message i f t he connect i on at t empt f ai l s.

    I f Not Socket . Connect ( ) ThenMessageBox. Show( Socket . Last Er r orSt r i ng)Exi t Sub

    End I f

    ' I f t hi s i s a secur e connect i on, t hen check t he st at us' of t he ser ver ' s cert i f i cat e. I f t he cer t i f i cat e i s not' val i d, war n t he user and t er mi nat e the connect i on.

    I f Socket . Secur e And _Socket . Cer t i f i cat eSt at us Secur i t yCer t i f i cat e. cer t i f i cat eVal i d ThenMessageBox. Show( "Ther e i s a pr obl em wi t h t he si t e cer t i f i cat e")Socket . Di sconnect ( )Exi t Sub

    End I f

    ' Send t he GET command t o t he ser ver usi ng t he Wr i t eLi ne' method, r equest i ng t he document t hat t he user has speci f i ed.

    I f Not Socket . Wr i t eLi ne( "GET " + TextBox4. Text ) ThenMessageBox. Show( Socket . Last Er r orSt r i ng)Socket . Di sconnect ( )Exi t Sub

    End I f

    ' Decl ar e t he st r i ng buf f er t hat wi l l cont ai n t he t ext

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    26/29

    AnIntroductionToInternetProgramming Page26

    ' r et ur ned by the server , and a Bool ean var i abl e.

    Di m st r Buf f er As St r i ng = Str i ng. Empt yDi m bCont i nue As Bool ean =Tr ue

    ' Cal l t he ReadLi ne met hod i n a l oop unt i l i t r et ur ns a' val ue of Fal se. For each l i ne of t ext t hat i s r ead,' append i t t o t he mul t i l i ne TextBox cont r ol .

    DobCont i nue = Socket . ReadLi ne( st r Buf f er )I f bCont i nue Then

    Text Box5. AppendText ( st r Buf f er + vbCr Lf )End I f

    Loop Unt i l bCont i nue = Fal se

    ' Di sconnect f r om t he ser ver , r el easei ng t he socket handl e' t hat was al l ocat ed f or t hi s sessi on.

    Socket . Di sconnect ( )

    End Sub

    Insummary,toestablishasecureconnectionyouneedtosettheSecurepropertytoavalueofTrue,

    andthenyoushouldcheckthevalueoftheCertificateStatuspropertyaftertheConnectmethodhas

    returned.Ifthecertificateisvalid,youcanproceednormally.Ifthereisaproblemwiththecertificate,

    youshouldeitherterminatetheconnectionoralerttheuserthereisaproblemandletthemmakethat

    decision.

    DebuggingApplications

    Oneoftheissuesthateverydeveloperhastocontendwithisproblemsthatariseinanapplicationafter

    it'sbeendistributedtoendusers.AnderrorsrelatedtoWindowsSocketsprogrammingcanbeeven

    moredifficulttotrackdownbecausetherearesomanyvariablesinvolved(suchastheplatform,

    operatingsystemversion,systemconfiguration,andsoon).Toaddressthesedifficultproblems,the

    SocketWrenchcontrolhasthebuiltinabilitytologtheWindowsSocketsAPIfunctioncallsthatare

    made.Therearethreepropertiesrelatedtocreatingalogfile:Trace,TraceFileandTraceFlags.Setting

    thesepropertiesenablesyourapplicationtodynamicallymanagefunctiontracingfeaturesavailableto

    thecontrol.TheTracepropertyisaBooleanflagwhichsimplyenablesordisablesthefunctiontracing

    feature.

    TheTraceFilepropertyspecifiesthenameofatracelogfileinwhicheachfunctionanditsparameters

    willbewritten.Ifthispropertyisnotexplicitlyset,thenafilenamedSocketTools.logwillbecreatedin

    thesystem'stemporarydirectory(thedirectoryspecifiedbytheTEMPenvironmentvariable).The

    TraceFlagspropertyspecifieswhattypeofloggingwillbeperformedbythecontrol,andmaybesetto

    oneoffourvalues:0(TRACE_ALL)inwhichallfunctionswillbelogged,1(TRACE_ERROR)inwhichonly

    errorswillbelogged,2(TRACE_WARNING)inwhichcasebothwarningsanderrorswillbewrittentothe

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    27/29

    AnIntroductionToInternetProgramming Page27

    logfile,and4(TRACE_HEXDUMPinwhichallfunctionswillbelogged,togetherwithASCIIand

    hexadecimaldisplaysofalldatathatissentorreceivedonsockets.Bydefault,allfunctioncallsare

    loggedbythecontrol(TRACE_ALL).

    Thetracefilehasthefollowingformat:

    EXAMPLE1 I NF: WSAAsyncSel ect ( 46, 0xcc4, 0x7e9, 0x27) r et urned 0

    EXAMPLE1 WRN: connect ( 46, 192. 0. 0. 1: 1234, 16) r eturned - 1 [ 10035]

    EXAMPLE1 ERR: accept( 46, NULL, 0x0) r et urned - 1 [ 10038]

    Thefirstcolumncontainsthenameoftheprocessbeingtraced.Thesecondcolumnidentifiesifthe

    recordisreportinginformation,awarning,oranerror.WhatfollowsisthenameoftheWindows

    Socketsfunctionbeingcalled,theargumentspassedtothefunctionandthefunction'sreturnvalue.Ifa

    warningorerrorisreported,theerrorcodeisappendedtotherecordwithinbrackets.

    Whenreadingatracelog,therearetwocommonthingsthatyouwillsee:

    1. Theerrorcode10035,whichcorrespondstotheWindowsSocketserrorWSAEWOULDBLOCKisanormaloccurrenceonconnectcalls,andshouldnotbetakenasacauseforconcernbyitself.

    2. Thenormalreturnvaluefortheselectfunctionisgreaterthanzero,typicallyavalueofone.Aselectcallthatreturnszerousuallyindicatesatimeout.Areturnvalueof1indicatesanerror

    condition.

    Ifparametersarepassedasintegervalues,theyarerecordedindecimal.Iftheparameterorreturn

    valueisamemoryaddress,itisrecordedasahexadecimalvalueprefixedwith"0x".Aspecialtypeof

    pointer,calledanullpointer,isrecordedasNULL.

    Thosefunctionswhichexpectsocketaddressesaredisplayedintheformataa.bb.cc.dd:nnnn.Thefirst

    fournumbersseparatedbyperiodsrepresenttheIPaddress,andthenumberfollowingthecolon

    representstheportnumberinhostbyteorder.Notethatinthesecondlineoftheaboveexample,the

    applicationisattemptingtoconnecttoasystemwiththeIPaddress192.0.0.1onport1234.

    Toenablelogginginyourapplication,youalsoneedtoredistributeanextrafilecalled

    SocketTools.TraceLog.dllandinstallitinthesamedirectoryasyourapplication.Ifyouhavesetthe

    TracepropertytoTrue,butthislibrarycannotbeloaded,thenSocketWrenchwillsilentlyresettheTrace

    propertytoFalse.NotethatthislibrarywillonlyprovideloggingcapabilitytotheSocketWrench

    component;itisnotageneralpurposelibraryforloggingWindowsSocketsfunctionsandwillnotlogthe

    functioncallsmadebyanyotherapplicationorcomponent.

    Thereareseveralwaysyoucouldincorporatetracelogginginyoursoftware.Thesimplestwouldbea

    menuitemoracommandlineswitch(like/Debug)inwhichtheTracepropertywouldbesettoTrue.A

    morecomplexapproachwouldbetoincludeadialogorpropertysheetwhichallowstheusertospecify

    thelogfilenameandoptions.Whenanendusercallsfortechnicalsupportandisencounteringa

    problemyouthinkmaybenetworkrelated,youcaninstructthemtoenabletheloggingfeatureand

    emailorfaxyouacopyofthelogfile.Inturn,ifitisaproblemyoudon'tunderstand,youcansendthe

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    28/29

    AnIntroductionToInternetProgramming Page28

    logfiletoaCatalystDevelopmentsupporttechnicianwhocananalyzethelogandprovideyouwith

    additionalinformationabouttheproblem.

    Rememberthatifyoudonotusetheloggingfeaturesatanytimeduringtheexecutionofyourprogram,

    thereisnoadditionalperformancepenalty.Ifyoudoenableloggingatsomepoint,thelibrarywillbe

    loadedand

    memory

    will

    be

    allocated

    by

    the

    logging

    functions.

    These

    functions

    open,

    append

    to

    the

    tracelogfile,flushandthenclosethefileforeachWindowsSocketsfunctioncallthatismade.This

    insuresthatthelastfunctioncalledisloggedincaseofageneralprotectionfaultorotherabnormal

    terminationoftheprogram.However,becauseofthefileI/Ooverhead,it'srecommendedthatyour

    programrenameorremovethelogfilebeforebeginninganewtrace.

    AdvancedDevelopmentUsingSocketToolsSocketWrenchispartofapackagedevelopedbyCatalystcalledSocketTools.Inadditiontothe

    comprehensive,butfairlylowlevel,accessthatSocketWrenchprovides,SocketToolsincludes

    components

    and

    libraries

    for

    many

    of

    the

    popular

    Internet

    application

    protocols.

    There

    are

    several

    differenteditionsofSocketToolsavailable,andalleditionsprovideroyaltyfreeredistributionlicensing

    andathirtydaymoneybackguarantee.EvaluationcopiesofalloftheSocketToolsEditionsareavailable

    fordownloadingfromourwebsite.

    SocketTools.NET Edition

    TheSocketTools.NETEditionisacollectionofmanagedcodeclasses,designedtosimplifythe

    integrationofInternetfunctionalityintoapplicationsbuiltusingtheVisualStudiodevelopment

    platform.SocketTools.NETisidealfortheVisualBasicorC#developerwhorequirestheeaseofuseand

    rapiddevelopmentfeaturesofacomponent,withoutthecomplexitiesofthenativesocketclassesand

    withoutrequiringindepthknowledgeofhowthevariousInternetprotocolsareimplemented.TheSocketToolsSecure.NETEditionhastheadditionalfeatureofintegratedsupportforsecure,

    encryptedconnectionsusingtheindustrystandardSecureSocketsLayer(SSL)andTransportLayer

    Security(TLS)protocols.Yourdataisprotectedbyindustrialstrength128bitencryption,and

    SocketToolsincludessupportforclientcertificatesandotheradvancedfeatures.Youcanalsocreate

    yourown,customsecureclientandserverapplicationsandthere'snoneedforyoutounderstandthe

    detailsofcertificatemanagement,dataencryptionorhowthesecurityprotocolswork.Allittakesisa

    fewlinesofcodetoenablethesecurityfeatureswithveryminimalchangestoanyexistingcode.

    SocketToolsLibraryEdition

    TheSocketTools

    Library

    Edition

    includes

    standard

    Windows

    dynamic

    link

    libraries

    (DLLs)

    which

    can

    be

    usedinawidevarietyofprogramminglanguagessuchasVisualStudio.NET,VisualC++,VisualBasicand

    Delphi.TheLibraryEditionisidealforthedeveloperwhorequiresthehighperformance,minimum

    resourceutilizationandflexibilityofalowerlevelinterface,withouttheinherentoverheadofActiveX

    controlsorCOMlibraries.

    Copyright2007CatalystDevelopmentCorporation.Allrightsreserved.

  • 8/22/2019 Tutorial 1-Schema

    29/29

    AnIntroductionToInternetProgramming Page29

    TheSocketToolsLibraryEditionAPIhasover800functionswhichcanbeusedtodevelopapplications

    thatmeetawiderangeofneeds.SocketToolscoversitall,includinguploadinganddownloadingfiles,

    sendingandretrievingemail,remotecommandexecution,terminalemulation,andmuchmore.

    Inadditiontotheabove,theSocketToolsSecureLibraryEditionhasintegratedsupportforsecure,

    encryptedconnections

    using

    the

    industry

    standard

    Secure

    Sockets

    Layer

    (SSL)

    and

    Transport

    Layer

    Security(TLS)protocols.ItprovidesaninterfaceforallofthemajorInternetprotocolsincludingHTTPS,

    FTPS,SMTPS,POP3SandIMAPS.Creatingasecureconnectiononlyrequiresafewadditionallinesof

    code,anddoesntrequirethatyouunderstandthecomplexdetailsofdataencryptionorcertificate

    validation.TheSecureLibraryEditionhandlesallofthedetails,enablingyoutoaddsecurityfeaturesto

    yourapplicationquicklyandeasily.

    SocketToolsScriptingEdition

    TheSocketToolsScriptingEditionincludesCOMcomponentswhichcanbeusedinawidevarietyof

    scriptinglanguagessuchasVBScript,JScriptandPHP.Inaddition,theScriptingEditioncomponentscan

    also

    be

    used

    with

    Visual

    Studio.NET,

    Visual

    C++

    and

    Visual

    Basic.

    The

    Scripting

    Edition

    is

    ideal

    for

    the

    developerwhorequirestheflexibility,easeofuseandrapiddevelopmentfeaturesofacomponent

    designedspecificallyforclientandserversidescripting.

    Inadditiontotheabove,theSocketToolsSecureScriptingEditionhasintegratedsupportforsecure,

    encryptedconnectionsusingtheindustrystandardSecureSocketsLayer(SSL)andTransportLayer

    Security(TLS)protocols.TheSecureEditionsimplementthemajorsecureprotocolssuchasHTTPS,FTPS,

    SMTPS,POP3S,IMAPSandmore.

    SocketToolsVisualEdition

    TheSocketToolsVisualEditionincludesActiveXcontrols(OCXs)whichcanbeusedinawidevarietyof

    programminglanguages

    such

    as

    Visual

    Studio.NET,

    Visual

    C++

    and

    Visual

    Basic.

    The

    Visual

    Edition

    is

    ideal

    forthedeveloperwhorequirestheflexibility,easeofuseandrapiddevelopmentfeaturesofa

    componentwithoutthecomplexitiesofworkingwiththeWindowsSocketsAPIorindepthknowledge

    ofhowthevariousInternetprotocolsareimplemented.

    TheSocketToolsVisualEditionconsistsofeighteenActiveXcontrolswhichcanbeusedtodevelop

    applicationsthatmeetawiderangeofneeds.SocketToolscoversitall,includinguploadingand

    downloadingfiles,sendingandretrievingemail,remotecommandexecutionandterminalemulation.

    Ifyou'redevelopingcommercialapplicationswhichrequiretheabilitytoestablishsecure,encrypted

    connections

    using

    the

    Secure

    Sockets

    Layer

    (SSL)

    and

    Transport

    Layer

    Security

    (TLS)

    protocols,

    the

    SocketToolsSecureVisualEditionincludessupportforallofthemajorsecureprotocolsincludingHTTPS,

    FTP,SMTPS,POP3SandIMAPS. Yourdataisprotectedbyindustrialstrength128bitencryption,and

    SocketToolsincludessupportforclientcertificatesandotheradvancedfeatures.Allittakesissettinga

    fewpropertiestoenablethesecurityfeatures,withveryminimalchangestoanyexistingcode.

    FormoreinformationaboutSocketTools,pleasevisittheCatalystDevelopmentwebsiteat

    http://www.catalyst.com/products/sockettools/