Академический Документы
Профессиональный Документы
Культура Документы
Thecharacteristicsofprotocolsfor
communicationbetweenprocessesina
distributedsystem
Applications,services
RMIandRPCand
RequestReplyProtocol
MarshallingandExternalDataRepresentation
UDPandTCP
OperatingSystem
Characteristics of IPC
Messagepassingbetweenapairofprocesses
supportedbySENDandRECEIVEoperations
Synchronoussendingandreceivingprocesses
synchronizeeverymessage,andBLOCK
AsynchronoussendingisNONBLOCKING,
receivingcanbebothBLOCKINGandNON
BLOCKING
Nonblockingreceivesarecomplex,somost
systemsemploytheblockingformofreceive
ReliabilitybothreliableandunreliableIPCsare
possible
Orderingoften,applicationsrequireSENDER
ORDERINGtobemaintained
socket
anyport
agreedport
socket
message
client
server
otherports
Internetaddress=138.37.94.248
Internetaddress=138.37.88.249
Messagesizesareoftenprenegotiated
Fragmentationcanoccur
Blockingsendsandreceivesarecommon
timeoutscanbeused,butthesecanbetricky
Datagramdiscardingoccurswhennoreceiving
processiswaiting
Bothsendomissionsandreceiveomissionscan
occur
Orderingmessagescanarriveoutoforder
ApplicationsthatuseUDPneedtoprovidetheir
ownchecks
Usages of UDP
Applicationsthatdonotsufferfromthe
overheadsassociatedwithguaranteedmessage
delivery
DNS
VoIP
DatagramPacketrequest=newDatagramPacket(m,args[0].length(),aHost,
serverPort);
aSocket.send(request);
byte[]buffer=newbyte[1000];
DatagramPacketreply=newDatagramPacket(buffer,buffer.length);
aSocket.receive(reply);
System.out.println("Reply:"+newString(reply.getData()));
}catch(SocketExceptione){System.out.println("Socket:"+e.getMessage());
}catch(IOExceptione){System.out.println("IO:"+e.getMessage());}
}finally{if(aSocket!=null)aSocket.close();}
}
}
aSocket=newDatagramSocket(6789);
byte[]buffer=newbyte[1000];
while(true){
DatagramPacketrequest=newDatagramPacket(buffer,
buffer.length);
aSocket.receive(request);
DatagramPacketreply=newDatagramPacket(request.getData(),
request.getLength(),request.getAddress(),request.getPort());
aSocket.send(reply);
}
}catch(SocketExceptione){System.out.println("Socket:"+e.getMessage());
}catch(IOExceptione){System.out.println("IO:"+e.getMessage());}
}finally{if(aSocket!=null)aSocket.close();}
}
}
Characteristicsofthenetworkarehidden/transparent
toapplications
Messagessizescanbesmallorlarge
AnACKschemedealswithlostmessages
Flowcontrolmechanismsthrottlefastsenders
Messageduplicationishandled,orderingis
maintained
Messagedestinationsare"streamendpoints"
More of TCP
Whenestablishingcommunication,onesideis
theclient,theotheristheserver
Thereafter,bothcanoperateaspeers,ifneeds
be
Pairsofsocketsareconnectedbypairsof
streams,oneforinput,theotherforoutput
Sequencenumbersdetectandrejectduplicate
packets
Timeoutsandretransmissionsdealwithlost
packets
TCPisnottotallyreliable,asitdoesnot
guaranteedeliveryofmessagesinthefaceofall
possibledifficulties
TCP's Unreliability
Whenaconnectionisbroken,aprocessis
notifiedifitattemptstoreadorwrite
Hasthenetworkfailedorhastheprocessatthe
otherendpointfailed?
Whereareprevioussentmessagesactually
received?
intserverPort=7896;
s=newSocket(args[1],serverPort);
DataInputStreamin=newDataInputStream(s.getInputStream());
DataOutputStreamout=
newDataOutputStream(s.getOutputStream());
out.writeUTF(args[0]);
//UTFisastringencodingseeSn4.3
Stringdata=in.readUTF();
System.out.println("Received:"+data);
}catch(UnknownHostExceptione){
System.out.println("Sock:"+e.getMessage());
}catch(EOFExceptione){System.out.println("EOF:"+e.getMessage());
}catch(IOExceptione){System.out.println("IO:"+e.getMessage());}
}finally{if(s!=null)try{s.close();}catch(IOExceptione)
{System.out.println("close:"+e.getMessage());}}
}
}
out.writeUTF(data);
}catch(EOFExceptione){System.out.println("EOF:"+e.getMessage());
}catch(IOExceptione){System.out.println("IO:"+e.getMessage());}
}finally{try{clientSocket.close();}catch(IOExceptione){/*closefailed*/}}
}
}
ExternalDataRepresentationandMarshalling
The Problem
Runningprograms(processes)arerepresented
as(binary)datastructures
Informationinmessagesisrepresentedasa
sequenceofbytes
Howdowetransformoneintotheotherandvice
versa?
Flattening
Datastructuresmustbeflattenedintoa
sequenceofbytesbeforetransmissionand
rebuiltonreceipt
Byteordering(littleorbigendian?)isanissue
Characterencodings(ASCII,Unicode)arean
issue,too
Valuesaretransmittedinthesender'sformat;the
recipientconvertsthatvaluesifnecessary
Anagreedstandardfortherepresentationofdata
structuresandprimitivevaluesiscalledan
"externaldatarepresentation"
Unmarshallingdisassemblingamessageon
arrivaltoproduceanequivalentcollectionofdata
itemsatthedestination
Java'sObjectSerializationworksonlywithinthe
Javaenvironment
XML(ExtensibleMarkupLanguage)atextual
formatforrepresentingstructureddatathatworks
withanyprogrammingtechnology
CORBA's CDR
CDRcanrepresent15primitivetypesanda
rangeofcompositetypes
Bothlittleandbigendiansupportisprovided
sendersindicateinwhichorderingthemessage
istransmitted
FloatingpointnumbersusetheIEEEstandard
Charactersarerepresentedinacodesetagreed
betweenthesenderandreceiver
DatatypeinformationisNOTtransmitted
Type
sequence
string
array
struct
enumerated
union
Representation
length(unsignedlong)followedbyelementsinorder
length(unsignedlong)followedbycharactersinorder(canalso
canhavewidecharacters)
arrayelementsinorder(nolengthspecifiedbecauseitisfixed)
intheorderofdeclarationofthecomponents
unsignedlong(thevaluesarespecifiedbytheorderdeclared)
typetagfollowedbytheselectedmember
4bytes
5
"Smit"
"h___"
6
"Lond"
"on__"
1934
notes
onrepresentation
lengthofstring
Smith
lengthofstring
London
unsignedlong
TheflattenedformrepresentsaPersonstructwithvalue:{Smith,London,1934}
Marshalling in CORBA
CORBA'sInterfaceDefinitionLanguage(IDL)is
usedto"automatically"producemarshallingand
unmarshallingoperations
TheCORBAIDLcompilerenablesthegeneration
oftherequiredcomponents
Considerthiscode:
Personp=newPerson("Smith","London",1934);
Explanation
Serializedvalues
Person
8byteversionnumber
h0
classname,versionnumber
intyear
1934
5Smith
6London
h1
valuesofinstancevariables
Thetrueserializedformcontainsadditionaltypemarkers;h0andh1arehandles
HTMLwasdesignedtodescribetheappearance
ofwebpages
XMLwasdesignedtodescribestructured
documentsandmarkuplanguages
XML Characteristics
XMLis"extensible"inthesensethatuserscan
definetheirowntags
XMLis"selfdescribing"
XMLwasintendedtobeusedbymultiple
applicationsfordifferentpurposes
XMLis"textual",socanbeeasilyreadby
humansandcomputers
<personid="123456789">
<name>Smith</name>
<place>London</place>
<year>1934</year>
<!acomment>
</person>
More XML
ThenamesusedinXMLareuserdefinedand
followthenormalnamingconventions
Binarydatais(typically)representedin"base64"
Alltagsarenestedcorrectly
AllXMLdocumentshaveasinglerootelement
withinwhichallotherelementsareenclosed
TheCDATAnotationallowsfortheinclusionof
specialcharacters
XML Prologs
<?XMLversion="1.0"encoding="UTF8"
standalone="yes"?>
XML Namespaces
Asetofnamesforacollectionofelementtypes
andattributes
Thenamespaceconventionallowsanapplication
tomakeuseofmultiplesetsofexternaldefinitions
indifferentnamespaceswithouttheriskofname
clashes
<personpers:id="123456789"xmlns:pers="http://www.cdk4.net/person">
<pers:name>Smith</pers:name>
<pers:place>London</pers:place>
<pers:year>1934</pers:year>
</person>
XML Schemas
Definestheelementsandattributesthatcan
appearinadocument
Defineshowtheelementsarenested,theorder
andnumberofelements
Defineswhetherornotanelementisemptyor
canincludetext
Foreachelement,theschemadefinesthetype
anddefaultvalue
AnXMLdocumentthatisdefinedtoconformto
aparticularschemamayalsobevalidatedby
meansofthatschema(usingoneofthemany
programmingAPIs)
Client-Server Communication
Normally,requestreplycommunicationis
synchronousbecausetheclientprocessblocks
untilthereplyarrivesfromtheserver
Itcanalsobereliableasthereplyfromtheserver
iseffectivelyanacknowledgmenttotheclient
Itispossibletobuildaclientserverprotocolover
areliableorunreliableprotocol
Establishingaconnectioninvolves(atleast)two
extrapairsofmessagesinadditiontothe
requestreplymessages
Flowcontrolisoverkill,asmostinvocationspass
onlysmallargumentsandresults
Request-Reply Communications
Client
doOperation
Server
Request
message
(wait)
(continuation)
Reply
message
getRequest
selectobject
execute
method
sendReply
messageType
int(0=Request,1=Reply)
requestId
int
objectReference
RemoteObjectRef
methodId
intorMethod
arguments
arrayofbytes
Request-Reply Communication
Characteristics
Whatisthefailuremodel?(Canomissionsoccur?
Ismessageorderingmaintained?)
Aretimeoutsemployedonoperations?
Howareduplicaterequestmessageshandled?
Howarelostreplymessageshandled?
Isahistoryofrequests(andreplies)maintained
oneitherend?
Idempotent Operations
Anoperationisidempotentifitcanbe
executedoneormoretimeswithoutside
effects
An Example Request-Reply
Protocol - HTTP
Allowsfortheinvocationofmethodsonweb
resources
Contentnegotiationisalsosupported
Passwordstyleauthenticationisavailable
InitiallyemployedasimpleConnectRequest
ReplyClosecycle
Thisprovedtobeexpensiveandinefficient
LatestversionofHTTPsupports"persistent
connections"
Resourcescanbebytesequencesandmay
becompressed
MultipurposeInternetMailExtensions(MIME)
supportsmultipartmessagesofvarying
formats
HTTP Methods
GET(whichisgenerallyidempotent)
HEAD,POST,PUT,DELETE,OPTIONSand
TRACE(arethemostwidelysupported)
URLorpathname
HTTPversion
headers messagebody
//www.dcs.qmw.ac.uk/index.html HTTP/1.1
HTTPversion
HTTP/1.1
OK
resourcedata
Group Communication
Thepairwiseexchangeofmessagesisrarely
thebestmodelforcommunicationfromone
processtoagroupofotherprocesses
Multicastmessagesprovideauseful
infrastructureforconstructingdistributedsystems
Uses of Multicasting
Faulttolerancebasedonreplicatedservers
Findingthediscoveryserviceinspontaneous
networking
Betterperformancethroughreplicateddata
Propagationofeventnotifications
ThesendertransmitsasingleIPpackettoaset
ofcomputersthatformamulticastgroup
Thesenderdoesnotknowtherecipients
identitiesnorhowbigthegroupis
TheclassDaddressspacewithinIPisreserved
forIPMulticast
Characteristics of IP Multicast
AvailablewithUDPonly
IdentifiedbyanIPaddress/portnumberend
point
Applicationscanjoinamulticastgroupby
openingasockettotheendpoint
Multicastaddressrange224.0.0.1through
224.0.0.255
Multicastssufferfromomissionfailures
Notallofthegroupmembersreceiveeverything
Reliablemulticastingispossibleoverheadsare
high
//argsgivemessagecontents&destinationmulticastgroup(e.g."228.5.6.7")
MulticastSockets=null;
try{
InetAddressgroup=InetAddress.getByName(args[1]);
s=newMulticastSocket(6789);
s.joinGroup(group);
byte[]m=args[0].getBytes();
DatagramPacketmessageOut=
newDatagramPacket(m,m.length,group,6789);
s.send(messageOut);
//getmessagesfromothersingroup
byte[]buffer=newbyte[1000];
for(inti=0;i<3;i++){
DatagramPacketmessageIn=
newDatagramPacket(buffer,buffer.length);
s.receive(messageIn);
System.out.println("Received:"+newString(messageIn.getData()));
s.leaveGroup(group);
}catch(SocketExceptione){System.out.println("Socket:"+e.getMessage());
}catch(IOExceptione){System.out.println("IO:"+e.getMessage());}
}finally{if(s!=null)s.close();}
}
Recipientsmaydropmessagesduetofullbuffers
Adatagramlostatonemulticastrouterprevents
allthoseroutersbeyondfromreceivingthe
datagram
Amulticastroutercanfail
Messageordering"errors"canresultintwo
routersreceivingasequenceofmulticastsina
verydifferentordertothatwhichwassent
TheSocketsystemcallslayeredoverthe
InternetTCPandUDPprotocols
Sendingamessage
Receivingamessage
s=socket(AF_INET,SOCK_DGRAM,0)
s=socket(AF_INET,SOCK_DGRAM,0)
bind(s,ClientAddress)
bind(s,ServerAddress)
sendto(s,"message",ServerAddress)
amount=recvfrom(s,buffer,from)
ServerAddressandClientAddressaresocketaddresses
Requestingaconnection
s=socket(AF_INET,SOCK_STREAM,0)
connect(s,ServerAddress)
Listeningandacceptingaconnection
s=socket(AF_INET,SOCK_STREAM,0)
bind(s,ServerAddress);
listen(s,5);
sNew=accept(s,ClientAddress);
write(s,"message",length)
n=read(sNew,buffer,amount)
ServerAddressandClientAddressaresocketaddresses
Therequestreply(RR)protocolspecialACKs
arenotrequired,thereplyandsubsequentnew
requestssufficeasACKs
Therequestreplyackreply(RRA)protocol
usedwhentheservermaintainsahistoryof
messages;the"ackreply"allowstheserverto
removeitemsfromitshistory