Tải bản đầy đủ - 0 (trang)
Chapter 9. Networking and Internet Programming

Chapter 9. Networking and Internet Programming

Tải bản đầy đủ - 0trang

conversation,andtheyuseprotocolstomakethishappen.Allof

REALbasic'snetworkingclassesuseInternetprotocols.

Tounderstandhowallofthisworks,Iwanttotalkabout

somethingmosteveryoneisfamiliarwithviewinganhtmlpage

inawebbrowser.LateroninthechapterIwillcreateaweb

serverusingclassesprovidedbyREALbasic.



ASimplifiedViewofaComputerNetwork

ActualimplementationsofnetworkscanbecomplexandI'mnot

anetworkingexpert,buthere'sahighlysimplifiedoverview.

TheInternetisanetworkofnetworks.Eachnetworkis

identifiedbyadomainname.Anetwork(oradomain)is

composedofanumberofhosts,whicharetheindividual

computersonthenetwork(sortof).Anygivenhostmayhave

oneormorenetworkedapplicationsrunningthingssuchasweb

serversandmailserversandsoon.Formultipleapplicationsto

worktogetherwithouttalkingovereachother,eachnetworked

applicationisassignedaport,whichisjustanumber(an

integer),andthatapplicationissaidtolistentothatport.When

arequestcomesin,itisdirectedatacertainportsothatthe

rightserverapplicationwillrespondtotherequest.Inaddition,

eachindividualcomputerhasafilesystemonwhichitstores

files.Allthesepiecesthedomain,thehost,theport,andthe

pathcanbeusedtoidentifyindividualresourcesonthenetwork.

Toseehowtheyareusedtogether,I'lltakeacloselookathow

theWorldWideWebworksandstepthroughtheprocessthatis

requiredforyoutorequestapage,receiveit,andviewitin

yourbrowser.



TheHypertextTransferProtocol

TheHypertextTransferProtocol(HTTP)istheprotocolthat

makestheWorldWideWebpossible,butitisn'ttheonly

protocolthatisneeded.ItalsoreliesontheTransmission

ControlProtocol(TCP)andtheInternetProtocol(IP),allof

whichIwilldiscussmomentarily.Inpracticalterms,HTTPisa

simpleprotocol,andthewayitworksisthis:Thereisaclient

(yourwebbrowser,usually)andaserver(awebserverofsome

sort)andtheclientsendsarequesttotheserverintheformof

aheader,whichisastringoftextthatincludestheinformation



theserverwillneedtorespondappropriately.Theserver

receivestheheader,processesit,andsendsdatabacktothe

client.

You'venodoubtusedawebbrowserbefore,soyouknowthat

thewayyouusethebrowseristhatyoutypetheaddressinto

theaddressfieldandpressEnter.Afterafewmoments,anew

htmlpageisdisplayedinthebrowser.Theaddressisknownas

aUniformResourceLocator(URL),andthisisusedbythe

softwaretofindaparticularresourceusuallyanhtmlfileona

serversomewhere.



URLs,DomainNames,andHosts

AURLconsistsofadomainname,ahostname,aportnumber,

andapath.Thisshouldbefamiliartoyounowbecauseinmy

simplifiedexplanationofanetwork,Iexplainedthatadomain,

ahost,aport,andapathwereallthatwereneededtofinda

givenresourceontheInternet.AURLisonewaytorepresent

thosevalues.

Whenyouareworkingonyourowncomputer,ithasadefault

hostname,localhost(youdon'tneedadomainnamebecause

therequestislocaltoyourcomputer).

Insomesituations,oneormoreoftheseelementsmaybe

missingintheURL,andthat'susuallybecauseofsomedefault

value.Forinstance,thedefaultportisport80,soyouoftensee

URLswithoutaportlisted.Youcanalsosetupyournetworkso

thatthehostnameisn'tnecessarybyroutingallHTTPrequests

toaparticularcomputer.Likewise,ifyouarerunningaweb

browserlocally,youcanrefersolelytothehost,withoutthe

domain,andsuccessfullymaketherequest(bydefault,thehost

iscalledlocalhost).Youdon'tevenneedtohaveacompletepath

toafilebecause,bydefault,ifthepathpointstoadirectory,it

isassumedthatyoumeanthefileindex.htmlwithinthat



directory.

AURLissupposedtobeauniquereferencetoaresource.

Usuallythatresourceisafileofsomesort,butitdoesn'thave

tobe.Manypagesonwebsitesarecreateddynamicallywhen

therequestismade,sotherereallyisn'tanactualpage

somewherethehtmlisgeneratedon-the-flyandsentbackto

thebrowser.



Ports

Atthehost,awebserverisrunning,listeningbydefaultonport

80.Itdoesn'thavetolistenonport80.Itcanlistenonport

8080ifitwantsto,andifthat'sthecase,youneedtospecify

theportintheURL,likeso:

http://localhost:8080/



IPAddresses

ThereisoneotherelementtoaddtothemixthatIhaven't

mentionedyet,andthatisIPaddresses.Domainnamesand

hostsusestringsbecausehumanbeingsfinditeasiertowork

withandrememberthem,butcomputersalwaysworkbetter

withnumbers.That'swhytherealaddressofacomputerisa

numericIPaddress,andthataddressismappedtothedomain

name.Domainnameservers(DNS)provideawayofmapping

domainnamestoIPaddressessothatbehindthescenes,when

youtypeinadomainname,thesoftwarelooksuptheIP

addressusingDNSandthenusestheIPaddresstolocatethe

computer.YoucaneasilyexchangetheactualIPaddressforthe

domainnameinyourbrowseranditwillworkjustaswell.



Inanyevent,afterthedomainisfound,followedbythehost

beingfound,anHTTPrequestissenttothewebserverthatis

runningonthathost.Therearethreekindsofrequeststhat

everywebservermustaccommodate:GET,PUT,andHEADERS.

ThepathportionoftheURListhensenttothewebserverand

thewebserverdecideswhattodowiththatpath.Inmost

cases,itusesthepathtofindanactualfileonthefilesystem,

whichitsendsbackouttotheclient.







TheProtocolStack

IsaidearlierthattheInternetisnotasingleprotocol.Rather,

it'sasuiteofprotocols.InthisoneHTTPrequest,several

protocolsgetused.Youcanthinkofitasastackofprotocols.In

theexampleoftheWorldWideWeb,thestackwouldbethis:

HTTP

TCP

IP

AtthebottomofthestackistheInternetProtocol,andthis

handlesallthelow-levelactivityinvolvedinfindingother

computersonthenetworkandgettingthemroutedthere.The

actualformatofthedatasentandhowthetwomachines

communicateaftertheyareconnectedishandledbythe

TransmissionControlProtocol(TCP).Ithastherathernarrow

scopeofbreakingthedataintopackets,sendingthepacketsto

theothermachine,andmakingsuretheyallarrivewherethey

aresupposedto,inthecorrectorder.Finally,atthetopofthe

stackistheHypertextTransferProtocol,whichtakesallthose

packetsthathavebeensentandrespondsbasedonthecontent

ofthosepackets.

Thisparticularstackofprotocolsisnottheonlystackthatis

usedontheInternet.Youcantakeastepbackandlookatthis

fromahigherlevelofabstractionandthinkofeachrowasa

layerthatperformsagenericfunction(OSIstuff).IfIwereto

dothat,thisiswhereeachiteminthestackcorrespondstothe

OSIlayers.

REALbasicprovidesseveralnetworkingclassesthatworkon

differentaspectsofthelayer.Thefollowinghierarchyshowsthe

classhierarchyandwhatpartofthesuiteofInternetprotocols



theclassworkswith.







TheInternet

SeveralprotocolsareusedontheInternet,andtheseareoften

referredtoastheInternetprotocolsuite.It'shelpfultothinkof

thiscollectionofprotocolsasastack,andeachlayerofthe

stackisresponsibleforcertainactivities.FromtheREALbasic

perspective,therearethreelayersthatareimportant(there's

actuallyaformalnetworkprotocolstackmodelcalledtheOSI

model,whichdividesupthenetworkstackintosevenlayers,

butthat'sfartooformalforourpurposes).Attheverybottom

ofthestackistheNetworkLayer.AbovethatistheTransport

Layer,andattheverytopistheApplicationLayer.



NetworkLayer

Whenreferringtotheunderlyingprotocolthatsupportsthe

Internet,peopleoftenrefertotwoprotocolsintandem:TCP/IP.

TCPistheTransmissionControlProtocol,whichI'lltalkabout

momentarily,andIPistheInternetProtocol,whichisthe

protocolthatsitsontheNetworkLayer.TheNetworkLayer

managesnetworkaddressesanddecideshowtopackageand

routedatafromonecomputertothenext.TheInternet

ProtocoldoesthisusingIPaddresses,URLs,andpackets.

Everycomputerhasaphysicaladdress,whichisknownasthe

IPaddress.ThedefaultIPaddressofyourownlocalcomputer

is127.0.0.1.Therearealsologicaladdresseswhichisreallyone

wayofsayingthattherearenamesthatgetmappedtoIP

addressesbecausetheyareeasierforhumanbeingsto

remember.IntheInternetworld,thisreferstohostanddomain

namesandURLs.Onyourlocalmachineisadefaulthostname

calledLocalhost.Ifyouareonacomputerthathasawebserver

running,youshouldbeabletotypeineitherofthefollowing

URLstogettothehomepage:



http://localhost/

http://127.0.0.1/



BothaddressesrefertothesamelocationontheInternet,and

itistheInternetProtocolthatmanagesthisprocess.Normally,

youusethename,suchashttp://realsoftware.com/,toreferto

alocationontheInternet.TheIPtakesthatname,looksupthe

IPaddress,andusestheaddresstoroutetherequesttothe

appropriatecomputer.Thelookupisdonebycheckingwitha

domainnameserver,whichislikeadictionarythatmaps

domainnamestoIPaddresses.

AftertheInternetProtocolhasmanagedtofindtheactual

addressofthecomputer,itneedstosendtherequesttoit.The

InternetProtocolbreaksuptherequestintosmallerpiecesof

datacalledpacketsandidentifiestheroutethepacketswill

take.Atthispoint,thenextlayeroftheInternetProtocolstack

takesover.



TransportLayer

TheTCPinTCP/IPstandsforTransmissionControlProtocol;itis

oneoftheprotocolsusedinthetransportlayer.Theotheris

calledUDP,whichstandsforUserDatagramProtocol.The

TransportLayerisresponsibleforactuallytransferringthedata

betweencomputers.REALbasicprovidesclassesforbothTCP

andUDPsockets.

ItiseasiesttounderstandwhatishappeningontheTransport

LayerbycomparingTCPtoUDP.It'scalledtheTransportLayer

becauseitdealswithhowdataismovedfromonecomputerto

thenext.TCPisaveryrobustprotocolthatincludesalotof

errorchecking,whichensuresthatallthedatasentbyone

computerisreceivedbytheothercomputerintheproperorder.



Becauseofallthiserrorchecking,itcanbealittleslowfor

someapplications.UDPistheprotocoldesignedforuseinthose

situations;itemphasizesspeedratherthanrobustness.

Therefore,itsendsalotofdata,butitdoesn'tchecktoensure

thatthedatahasarrivedasexpected.Thismeansthatsome

datagetslostintransmission.Inmanycases,thislossofdata

isconsideredanacceptabletrade-offtogetenhancedspeed.

ThingssuchasstreamingvideoandaudiomakeuseofUDP.



ApplicationLayer

TheApplicationLayersitsatthetopofthestack.Thisisthe

protocolthathandlesapplicationtasks.ExamplesofApplication

LayerprotocolsareHTTP,SMTP(SimpleMailTransferProtocol),

andPOP3(PostOfficeProtocol,version3).Theseprotocolsare

usedincommonInternetapplications,suchaswebbrowsers

andemailclients.REALbasicprovidesclassesforthese

protocolsaswell.







REALbasicNetworkingClasses

TheclasshierarchyprovidedbyREALbasicfallsneatlyintothis

layeredapproachtothinkingaboutnetworks,asillustratedin

Figure9.1:



Figure9.1.Internetsuiteofprotocols.



AtthetopofthehierarchyistheSocketCoreclass,whichisan

abstractclassthatisneverinstantiated.Therearetwo

subclassestoSocketCore:TCPSocketandUDPSocket.These

arethetwobasicsocketclassesthatyouwillbeusingtowrite

yournetworkedapplication.TCPSockethasseveralsubclasses

thatworkontheApplicationLayer,whichmeansthattheyare

designedtoperformspecifickindsofactivitiesontheInternet,

suchasrequestwebpagesandsendorreceiveemail.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 9. Networking and Internet Programming

Tải bản đầy đủ ngay(0 tr)

×