C Network Programming With Patterns, Frameworks,

Transcription

C Network Programming with Patterns,Frameworks, and ACEDouglas C. tl.edu/ schmidt/Department of EECSVanderbilt University(615) 343-8197SponsorsNSF, DARPA, ATD, BBN, Boeing, Cisco, Comverse, GDIS, Experian, Global MT,Hughes, Kodak, Krones, Lockheed, Lucent, Microsoft, Mitre, Motorola, NASA, Nokia,Nortel, OCI, Oresis, OTI, QNX, Raytheon, SAIC, Siemens SCR, Siemens MED,Siemens ZT, Sprint, Telcordia, USENIX

Advanced ACE TutorialDouglas C. SchmidtRoadmap to Levels of Middleware ObservationsAPPLICATIONSDOMAIN-SPECIFIC MIDDLEWARE SERVICESCOMMON MIDDLEWARE RVICEConsConsConsDISTRIBUTION MIDDLEWAREHOST INFRASTRUCTURE MIDDLEWAREOPERATING SYSTEMS & PROTOCOLS– Historically, appsbuilt atop OS– Today, apps builtatop middleware– Middleware hasmultiple layers Just like networkprotocol stacksHARDWARE DEVICESwww.cs.wustl.edu/ schmidt/PDF/middleware-chapter.pdfVanderbilt University1

Advanced ACE TutorialDouglas C. SchmidtMotivation for ConcurrencySERVER Leverage hardware/softwaremaxfdp1CLIENTCLIENTread ESTCLIENT(1) ITERATIVE SERVER Increase performance– e.g., overlap computation andcommunicationSERVER Improve response-timeCLIENTWORKREQUESTCLIENT– e.g., multi-processors and OSthread supportWORKREQUEST– e.g., GUIs and network serversWORKREQUESTCLIENT(2) CONCURRENT SERVERVanderbilt UniversityWORKREQUEST Simplify program structureCLIENT– e.g., sync vs. async2

Advanced ACE TutorialDouglas C. SchmidtMotivation for Distribution PRINTERCOMPUTERCD ROMFILESYSTEM(1) STAND-ALONE APPLICATION LAYSERVICENETWORKFI LESERVICEPRINTSERVICECD ROMPRINTERFILE SYSTEM(2) DISTRIBUTED APPLICATION ARCHITECTUREVanderbilt University CollaborationinterworkingPerformanceand locality! connectivity and! multi-processingReliability and availabilityreplicationScalability and uration and reconfiguration!Cost effectivenessopensystems and resource sharing3

Advanced ACE TutorialDouglas C. SchmidtChallenges and Solutions Developing efficient, robust, and extensible concurrent networkingapplications is hard– e.g., must address complex topics that are less problematic or notrelevant for non-concurrent, stand-alone applications OO techniques and OO language features help to enhance softwarequality factors– Key OO techniques include patterns and frameworks– Key OO language features include classes, inheritance, dynamicbinding, and parameterized types– Key software quality factors include modularity, extensibility,portability, reusability, and correctnessVanderbilt University4

Advanced ACE TutorialDouglas C. SchmidtCaveats OO is not a panacea– Though when used properly it helps minimize “accidental”complexity and improve software quality factors It’s also essential to understand advanced OS features to enhancefunctionality and performance, singSynchronizationShared memoryExplicit dynamic linkingCommunication protocols and IPC mechanismsVanderbilt University5

Advanced ACE TutorialDouglas C. SchmidtTutorial Outline Brief overview of key OO networking and concurrency concepts andOS platform mechanisms– Emphasis is on practical solutions Examine a range of examples in detail––––Networked Logging ServiceConcurrent Web ServerApplication-level Telecom GatewayCall Center Manager Event Server Discuss general concurrent programming strategies Provide URLs for further reading on the topicVanderbilt University6

Advanced ACE TutorialDouglas C. SchmidtSoftware Development Environment The topics discussed here are largely independent of OS, network,and programming language– Currently used successfully on UNIX/POSIX, Windows, andRTOS platforms, running on TCP/IP networks using C Examples are illustrated using freely available ADAPTIVECommunication Environment (ACE) OO framework components– Although ACE is written in C , the principles covered in thistutorial apply to other OO languages– e.g., Java, Eiffel, Smalltalk, etc. In addition, other networks and backplanes can be used, as wellVanderbilt University7

Advanced ACE TutorialDouglas C. SchmidtSources of Complexity Inherent complexityPRINTERCOMPUTERCD ROMFILESYSTEM(1) STAND-ALONE APPLICATION LAYSERVICENETWORKFI LESERVICEPRINTSERVICECD ROMPRINTERFILE SYSTEM(2) DISTRIBUTED APPLICATION ARCHITECTUREVanderbilt ationDeadlock Accidental Complexity– Low-level APIs– Poor debugging tools– Algorithmicdecomposition– Continuousre-invention8

Advanced ACE TutorialDouglas C. SchmidtSources of Inherent ComplexityInherent complexity results from fundamental domain challenges,e.g.:Concurrent programmingDistributed programming Eliminating “race conditions” Addressing the impact of latency Deadlock avoidance Fault tolerance and high availability Fair scheduling Load balancing and servicepartitioning Performance optimizationand tuningVanderbilt University Consistent ordering of distributedevents9

Advanced ACE TutorialDouglas C. SchmidtSources of Accidental ComplexityAccidental complexity results from limitations with tools and techniquesused to develop concurrent applications, e.g., Lack of portable, reentrant, type-safe and extensible system callinterfaces and component libraries Inadequate debugging support and lack of concurrent anddistributed program analysis tools Widespread use of algorithmic decomposition– Fine for explaining concurrent programming concepts andalgorithms but inadequate for developing large-scale concurrentnetwork applications Continuous rediscovery and reinvention of core concepts andcomponentsVanderbilt University10

Advanced ACE TutorialDouglas C. SchmidtOO Contributions to Concurrentand Distributed ApplicationsConcurrent network programming is Patterns and frameworks elevatetraditionally performed usingdevelopment level to focus onlow-level OS mechanisms, e.g.,application concerns, e.g., fork/exec Shared memory and semaphores Memory-mapped files Signals sockets/select Low-level thread APIsVanderbilt University Service functionality andpolicies Service configuration Concurrent eventdemultiplexing and eventhandler dispatching Service concurrency andsynchronization11

Advanced ACE TutorialDouglas C. SchmidtOverview of Patterns Patterns represent solutions to problems that arise when developingsoftware within a particular context– i.e., “Patterns problem/solution pairs within a context” Patterns capture the static and dynamic structure and collaborationamong key participants in software designs– They are particularly useful for articulating how and why toresolve non-functional forces Patterns facilitate reuse of successful software architectures anddesignsVanderbilt University12

Advanced ACE TutorialDoExample: the Proxy Pattern1: METHODCALL: BROKER: QUOTER4: METHODRETURN3:CLIENTNETWORKPROXYRESPONSE: QUOTER2: FORWARDREQUESTSERVERIntent: Provide a surrogate for another object thatcontrols access to itVanderbilt University

Advanced ACE TutorialDouglas C. SchmidtOverview of Frameworks and Components A framework is:– “An integrated collection of components that collaborate toproduce a reusable architecture for a family of related applications” Frameworks differ from conventional class libraries:1. Frameworks are “semi-complete” applications2. Frameworks address a particular application domain3. Frameworks provide “inversion of control” Frameworks facilitate reuse of successful networked applicationsoftware designs and implementations– Applications inherit from and instantiate framework componentsVanderbilt University14

Advanced ACE TutorialDouglas C. SchmidtClass Libraries versus EEVENTLOOPNETWORKCLASSESCODEIPCCLASSES(A) CLASSLIBRARY ASSESDATABASE(B) FRAMEWORKVanderbilt University Class libraries––––Reusable building blocksDomain-independentLimited in scopePassive FrameworksLOOPADTKey distinctionsEVENTLOOPARCHITECTURE– Reusable, “semi-complete”applications– Domain-specific– Broader in scope– Active15

Advanced ACE TutorialDouglas C. SchmidtThe ADAPTIVE Communication Environment(ACE)JAWS ADAPTIVEWEB GGINGSERVERC THE ACE ARDS BASED MIDDLEWARESOCK SAP/TLI URATORREACTOR/PROACTORSHAREDMALLOCMEMMAPFILESAPOS ADAPTATION LAYERCAPISPROCESSES/THREADSWIN32 NAMEDPIPES & UNIXSTREAM MMUNICATIONSUBSYSTEMSELECT/IO COMPDYNAMICLINKINGSHAREDMEMORYFILE SYSAPISVIRTUAL MEMORY & FILESUBSYSTEMGENERAL OPERATING SYSTEM SERVICESwww.cs.wustl.edu/ schmidt/ACE.htmlVanderbilt University16

Advanced ACE TutorialDouglas C. SchmidtACE Statistics ACE library contains 250,000lines of C – Over 40 person-years of effort Ported to UNIX, Windows, MVS, andRT/embedded platforms– e.g., VxWorks, LynxOS, Chorus Large user and open-sourcedeveloper community– schmidt/ACE-users.html Currently used bydozens of companies– Bellcore, BBN,Boeing, Ericsson,Hughes, Kodak,Lockheed, Lucent,Motorola, Nokia,Nortel, Raytheon,SAIC, Siemens, etc. Supported commerciallyby Riverace– www.riverace.comVanderbilt University17

Advanced ACE TutorialDouglas C. SchmidtThe Key Frameworks in atorStreamsTask ACE contains a number of frameworks that can be used separatelyor together This design permits fine-grained subsetting of ACE components– Subsetting helps minimize ACE’s memory footprint– ACE ROOT/doc/ACE-subsets.htmlVanderbilt University18

Advanced ACE TutorialDouglas C. SchmidtPatterns for Communication LockingStrategizedLockingEventPatternsVanderbilt UniversityObjectLifetimeManagerInitialization SynchronizationPatternsPatternsObservation Failures rarely result fromunknown scientificprinciples, but from failingto apply provenengineering practices andpatternsBenefits of Patterns Facilitate design reuse Preserve crucial designinformation Guide design choices19

Advanced ACE TutorialDouglas C. SchmidtThe ACE ORB (TAO)TAO Overview !in argsCLIENTOBJREFoperation()OBJECT(SERVANT)out args returnvalueIDLIDLSTUBSIOPORB L-TIME ORB COREPLUGGABLEORB & XPORTPROTOCOLSOS KERNELREAL-TIME I/OSUBSYSTEMHIGH-SPEEDNETWORK INTERFACEPLUGGABLEORB & XPORTPROTOCOLSACECOMPONENTSNETWORKIOPOS KERNELREAL-TIME I/OSUBSYSTEMHIGH-SPEEDNETWORK INTERFACEwww.cs.wustl.edu/ schmidt/TAO.htmlVanderbilt University A real-time,high-performanceORB Leverages ACE– Runs on POSIX,Windows,RTOSsRelated efforts ! QuO at BBN MIC/GME atVanderbilt XOTS20

Advanced ACE TutorialDouglas C. SchmidtTAO Statistics TAO order of magnitude 50 person-years of effort– Core ORB 300,000 LOC Currently used by manycompanies– IDL compiler 200,000LOC– e.g., Boeing, BBN, Lockheed,– CORBA Object Services Lucent, Motorola, Raytheon,250,000 LOCSAIC, Siemens, etc.– Leverages ACE heavily Supported commercially by OCI Ported to UNIX, Windows, &and PrismTechRT/embedded platforms– www.ociweb.com– e.g., VxWorks, LynxOS,– www.prismtechnologies.comChorus, WinCEVanderbilt University21

Advanced ACE TutorialDouglas C. SchmidtJAWS Adaptive Web ServerWWWCLIENT1: GET schmidtHTTP/1.02: SPATCHERREQUESTERGRAPHICSADAPTERCOMMUNICATION PROTOCOL(E.G., HTTP)OS KERNELOS KERNELOS I/O SUBSYSTEMOS I/O SUBSYSTEMNETWORK ADAPTERSNETWORK ADAPTERSNETWORKwww.cs.wustl.edu/ jxh/research/Vanderbilt University JAWS Overview– A high-performanceWeb server Flexible concurrencyand dispatchingmechanisms– Leverages the ACEframework Ported to most OSplatforms– Used commercially byCacheFlow www.cacheflow.com22

Advanced ACE TutorialDouglas C. SchmidtJava ACEDISTRIBUTEDSERVICES ANDCOMPONENTSFRAMEWORKSAND VERSERVERACCEPTORSERVICECONNECTORHANDLERJava ACEOverview A Java versionof ACEADAPTIVE SERVICE EXECUTIVE (ASX)JAVASYNCHWRAPPERS WRAPPERSSOCK RJAVA VIRTUAL MACHINE (JVM)www.cs.wustl.edu/ schmidt/JACE.htmlwww.cs.wustl.edu/ schmidt/C 2java.htmlwww.cs.wustl.edu/ schmidt/PDF/MedJava.pdfVanderbilt University– Used formedicalimagingprototype23

Advanced ACE TutorialDoNetworked Logging ONREMOTEP3IPCSERVER LOGGINGDAEMONHAOST AHOSTSERVERCLIENTREMOTEIPCAHOSTB LOGGINGDAEMONP3Intent: Server logging daemon collects, formats,and outputs logging records forwarded from clientlogging daemons residing throughout a network orInternetVanderbilt University

Advanced ACE TutorialDouglas C. SchmidtNetworked Logging Service Programming APIThe logging API is similar to printf(), e.g.:ACE ERROR ((LM ERROR, "(%t) fork failed"));Generates on logging server host:Oct 31 14:50:13 1992@tango.ics.uci.edu@2766@LM ERROR@client::(4) fork failedandACE DEBUG ((LM DEBUG,"(%t) sending to server %s", server host));generates on logging server host:Oct 31 14:50:28 1992@zola.ics.uci.edu@18352@LM DEBUG@drwho::(6) sending to server bastilleVanderbilt University25

Advanced ACE TutorialDouglas C. SchmidtConventional Logging Server DesignTypical algorithmic pseudo-code forThe “grand mistake:”networked logging server: Avoid the temptation tovoid logging server (void) {“step-wise refine” thisinitialize acceptor endpointalgorithmicallydecomposedloop forever {pseudo-code directly intowait for eventsthe detailed design andhandle data eventsimplementation of thehandle connection eventslogging server!}}Vanderbilt University26

Advanced ACE TutorialDoThe select()-based Logging NG DAEMONmaxhandlep1acceptorread GRECORDSCLIENTLOGGINGRECORDSCLIENTSerializes server processing at select()demuxing levelVanderbilt University

Advanced ACE TutorialConventional Logging ServerImplementationNote the excessive amount of detail required toprogram at the socket level.// Main programstatic const int PORT 10000;typedef u long COUNTER;typedef int HANDLE;// Counts the # of logging records processedstatic COUNTER request count;// Acceptor-mode socket handlestatic HANDLE acceptor;// Highest active handle number, plus 1static HANDLE maxhp1;// Set of currently active handlesstatic fd set activity handles;// Scratch copy of activity handlesstatic fd set ready handles;Vanderbilt UniversityDo

Advanced ACE TutorialMain Event Loop of Logging Serverint main (int argc, char *argv[]){initialize acceptor(argc 1 ? atoi (argv[1]) : PORT);// Loop forever performing logging// server processing.for (;;) {// struct assignment.ready handles activity handles;// Wait for client I/O events.select (maxhp1, &ready handles, 0, 0, 0);// First receive pending logging records.handle data ();// Then accept pending connections.handle connections ();}}Vanderbilt UniversityDo

Advanced ACE TutorialInitialize Acceptor Socketstatic void initialize acceptor (u short port){struct sockaddr in saddr;// Create a local endpoint of communication.acceptor socket (PF INET, SOCK STREAM, 0);// Set up the address info. to become server.memset ((void *) &saddr, 0, sizeof saddr);saddr.sin family AF INET;saddr.sin port htons (port);saddr.sin addr.s addr htonl (INADDR ANY);// Associate address with endpointbind (acceptor,(struct sockaddr *) &saddr,sizeof saddr);// Make endpoint listen for connection requests.listen (acceptor, 5);// Initialize handle sets.FD ZERO (&ready handles);FD ZERO (&activity handles);FD SET (acceptor, &activity handles);maxhp1 acceptor 1;}Vanderbilt UniversityDo

Advanced ACE TutorialHandle Data Processingstatic void handle data (void) {// acceptor 1 is the lowest client handlefor (HANDLE h acceptor 1; h maxhp1; h )if (FD ISSET (h, &ready handles)) {ssize t n handle log record (h, 1);// Guaranteed not to block in this case!if (n 0) request count;// Count the # of logging recordselse if (n 0) {// Handle connection shutdown.FD CLR (h, &activity handles);close (h);if (h 1 maxhp1) {// Skip past unused handleswhile (!FD ISSET (--h,&activity handles))continue;maxhp1 h 1;}}}}Vanderbilt UniversityDo

Advanced ACE TutorialDoReceive and Process Logging Recordsstatic ssize t handle log record (HANDLE in h,HANDLE out h) {ssize t n;size t len;Log Record lr;// The first recv reads the length (stored as a// fixed-size integer) of adjacent logging record.n recv (in h, (char *) &len, sizeof len, 0);if (n 0) return n;len ntohl (len); // Convert byte-ordering// The second recv then reads len bytes to// obtain the actual record.for (size t nread 0; nread len; nread nn recv (in h, ((char *) &lr) nread,len - nread, 0);// Decode and print record.decode log record (&lr);if (write (out h, lr.buf, lr.size) -1)return -1;else return 0;}Vanderbilt University

Advanced ACE TutorialHandle Connection Acceptancestatic void handle connections (void){if (FD ISSET (acceptor, &ready handles)) {static struct timeval poll tv {0, 0};HANDLE h;// Handle all pending connection requests// (note use of select’s polling feature)do {// Beware of subtle bug(s) here.h accept (acceptor, 0, 0);FD SET (h, &activity handles);// Grow max. socket handle if necessary.if (h maxhp1)maxhp1 h 1;} while (select (acceptor 1, &ready handles,0, 0, &poll tv) 1);}Vanderbilt UniversityDo

Advanced ACE TutorialConventional Client LoggingDaemon ImplementationThe main() method receives logging records fromclient applications and forwards them on to thelogging serverint main (int argc, char *argv[]){HANDLE stream initialize stream endpoint(argc 1? atoi (argv[1]): PORT);Log Record lr;// Loop forever performing client// logging daemon processing.for (;;) {// . get logging records from client//application processes .size t size htonl (lr.size);send (stream, &size, sizeof size);encode log record (&lr);send (stream, ((char *) &lr), sizeof lr);}}Vanderbilt UniversityDo

Advanced ACE TutorialDoClient Connection Establishmentstatic HANDLE initialize stream endpoint(const char *host, u short port){struct sockaddr in saddr;// Create a local endpoint of communication.HANDLE stream socket (PF INET, SOCK STREAM, 0);// Set up the address info. to become client.memset ((void *) &saddr, 0, sizeof saddr);saddr.sin family AF INET;saddr.sin port htons (port);hostent *hp gethostbyname (host);memcpy ((void *) &saddr,htonl (hp- h addr),hp- h length);// Associate address with endpointconnect (stream,(struct sockaddr *) &saddr,sizeof saddr);return stream;}Vanderbilt University

Advanced ACE TutorialDouglas C. SchmidtLimitations with Algorithmic DecompositionAlgorithmic decomposition tightly couples application-specificfunctionality and the following configuration-related characteristics: Application Structure– The number of services per process– Time when services are configured into a process Communication and Demultiplexing Mechanisms– The underlying IPC mechanisms that communicate with otherparticipating clients and servers– Event demultiplexing and event handler dispatching mechanisms Concurrency and Synchronization Model– The process and/or thread architecture that executes service(s) atrun-timeVanderbilt University36

Advanced ACE TutorialDouglas C. SchmidtOvercoming Limitations via OO The algorithmic decomposition illustrated above specifies manylow-level details– Moreover, the excessive coupling impedes reusability,extensibility, and portability. In contrast, OO focuses on application-specific behavior, e.g.,int Logging Handler::handle input (void){ssize t n handle log record (peer ().get handle (),ACE STDOUT);if (n 0) request count; // Count the # of logging recordsreturn n 0 ? -1 : 0;}Vanderbilt University37

Advanced ACE TutorialDouglas C. SchmidtOO Contributions to Software Patterns facilitate the large-scale reuse of software architecture– Even when reuse of algorithms, detailed designs, andimplementations is not feasible Frameworks achieve large-scale design and code reuse– In contrast, traditional techniques focus on the functions andalgorithms that solve particular requirements Note that patterns and frameworks are not unique to OO!– However, objects and classes are useful abstraction mechanismsVanderbilt University38

Advanced ACE TutorialDouglas C. SchmidtPatterns in the Networked Logging ctorSTRATEGICPATTERNSTACTICAL WrapperFacade Strategic and tactical are relative to the context and abstraction levelVanderbilt University39

Advanced ACE TutorialDouglas C. SchmidtSummary of Pattern Intents Wrapper Facade ! “Encapsulates the functions and data providedby existing non-OO APIs within more concise, robust, portable,maintainable, and cohesive OO class interfaces” Reactor ! “Demultiplexes and dispatches requests that aredelivered concurrently to an application by one or more clients” Acceptor ! “Decouple the passive connection and initialization of apeer service in a distributed system from the processing performedonce the peer service is connected and initialized” Component Configurator ! “Decouples the implementation ofservices from the time when they are configured” Active Object ! “Decouples method execution from methodinvocation to enhance concurrency and simplify synchronizedaccess to an object that resides in its own thread of control”Vanderbilt University40

Advanced ACE TutorialDouglas C. SchmidtComponents in the OO Logging Server Application-specific components– Process logging records received from clients Connection-oriented application components– ACE Svc Handler (service handler) Performs I/O-related tasks with clients– ACE Acceptor factory Passively accepts connection requests Dynamically creates a service handler for each client and“activates” it Application-independent ACE framework components– Perform IPC, explicit dynamic linking, event demultiplexing, eventhandler dispatching, multi-threading, etc.Vanderbilt University41

Advanced ACE PECIFICCOMPONENTSClass Diagram for OO Logging ServerLogging HandlerSOCK Acceptor1LoggingAcceptorSOCK StreamNull Synchn activates LoggingHandlerSVC HANDLERPEER ERACCEPTORPEERSTREAMConnectionStreamIPC SAPServiceConfiguratorConcurrencyVanderbilt UniversityPEER STREAMSYNCH STRATReactor

Advanced ACE TutorialDouglas C. SchmidtAddressing Robustness, Portability,and Maintainability Challenges Problem– Building distributed applications using low-level APIs is hard Forces– Low-level APIs are verbose, tedious, and error-prone to program– Low-level APIs are non-portable and non-maintainable Solution– Apply the Wrapper Facade pattern to encapsulate low-levelfunctions and data structuresVanderbilt University43

Advanced ACE TutorialDouglas C. SchmidtThe Wrapper Facade PatternIntent Encapsulates the functionsand data provided byexisting lower-level,non-OO APIs within moreconcise, robust, portable,maintainable, and cohesivehigher-level OO classinterfacesclient1: method k()WrapperFacademethod 1().method m()2: function k()Functionsfunction 1().function n()POSA2 (www.cs.wustl.edu/ schmidt/POSA/)Forces Resolved Avoid tedious, error-prone, and non-portable system APIs Create cohesive abstractionsVanderbilt University44

Advanced ACE TutorialDoMotivating the Wrapper Facade Pattern:the Socket API2: ACTIVE1: nd()/recv()close()CLIENT3: pt()send()/recv()close()SERVERSockets are the most common networkprogramming API and are available on most OSplatformsVanderbilt University

Advanced ACE TutorialDouglas C. SchmidtProblem with Sockets: Lack of Type-safetyint buggy echo server (u short port num) I/O handles are{ // Error checking omitted.not amenable tosockaddr in s addr;strong typeint acceptor checking atsocket (PF UNIX, SOCK DGRAM, 0);compile-times addr.sin family AF INET;s addr.sin port port num; The adjacents addr.sin addr.s addr INADDR ANY;bind (acceptor, (sockaddr *) &s addr,code containssizeof s addr);many subtle,int handle accept (acceptor, 0, 0);common bugsfor (;;) {char buf[BUFSIZ];ssize t n read (acceptor, buf, sizeof buf);if (n 0) break;write (handle, buf, n);}}Vanderbilt University46

Advanced ACE TutorialDouglas C. SchmidtProblem with Sockets: Steep Learning CurveMany socket/TLI API functions have complex semantics, e.g.: Multiple protocol families and address families– e.g., TCP, UNIX domain, OSI, XNS, etc. Infrequently used features, e.g.:––––Broadcasting/multicastingPassing open file handlesUrgent data delivery and receptionAsynch I/O, non-blocking I/O, I/O-based and timer-based eventmultiplexingVanderbilt University47

Advanced ACE TutorialDouglas C. SchmidtProblem with Sockets: Portability Having multiple “standards,” i.e., sockets and TLI, makes portabilitydifficult, e.g.,– May require conditional compilation– In addition, related functions are not included in POSIX standards e.g., select(), WaitForMultipleObjects(), and poll() Portability between UNIX and Windows Sockets is problematic, e.g.:–––––Header filesError numbersHandle vs. descriptor typesShutdown semanticsI/O controls and socket optionsVanderbilt University48

Advanced ACE Tutorial49Douglas C. SchmidtProblem with Sockets: Poorly StructuredVanderbilt University Non-portable There is no consistency among names. Socket API is linear rather than e()getservbyname()

Advanced ACE TutorialDoDATAGRAMN/IO ONTCTINE ICAIVENSNSCO MU LEPAMORERCOXFETIVCASTREAM CONNECTEDDATAGRAMTYPE OF COMMUNICATION SERVICESocket TaxonomyCOMMUNICATION DOMAINLOCAL/REMOTELOCALsocket(PF UNIX)/bind()sendto()/recvfrom()socket(PF UNIX)/bind()socket(PF INET)/bind()sendto()/recvfrom()socket(PF INET)/bind()socket(PF UNIX)socket(PF send()/recv()socket(PF UNIX)socket(PF INET)bind()/connect()bind()/connect()socket(PF F UNIX)bind()/connect()socket(PF F INET)bind()/connect()The Socket API can be classified along threedimensions1. Connection role2. Communication domain3. Type of serviceVanderbilt University

Advanced ACE TutorialDoN/ NOICT ATIOENICIVENSNCO MU AGRAMSTREAMTYPE OF COMMUNICATION SERVICESolution: ACE Socket Wrapper FacadesCOMMUNICATION DOMAINLOCAL/REMOTELOCALramgDKCSOSOCK Dgram BcastSOCK Dgram McastSOCK DgramLSOCK DgramLSOCK CODgramSOCK CODgramLSOCK AcceptorLSOCK StreamLSOCK ConnectorSOCK AcceptorSOCK StreamSOCK ConnectorThe ACE C wrapper facades more explicitlymodel the key socket components using OOclassesVanderbilt University

Advanced ACE TutorialDoThe ACE Connection-OrientedSocket Wrapper FacadesACE IPC SAPACE SOCK IOACE SOCKACE SOCK AcceptorACE SOCK StreamACE AddrACE INET AddrACE SOCK ConnectorParticipants Passive and active connection factories– ACE SOCK Acceptor and ACE SOCK ConnectorStreaming classes– ACE SOCK Stream and ACE SOCK IOAddressing classes– ACE Addr and ACE INET AddrVanderbilt University

Advanced ACE TutorialDouglas C. SchmidtThe ACE Connection-Oriented SocketWrapper Facade Factoriesclass ACE SOCK Connector{public:// Traitstypedef ACE INET Addr PEER ADDR;typedef ACE SOCK Stream PEER STREAM;int connect(ACE SOCK Stream &new sap,const ACE INET Addr &raddr,ACE Time Value *timeout,const ACE INET Addr &laddr);// .};Vanderbilt Universityclass ACE SOCK Acceptor: public ACE SOCK{public:// Traitstypedef ACE INET Addr PEER ADDR;typedef ACE SOCK Stream PEER STREAM;ACE SOCK Acceptor (const ACE INET Addr &);int open (const ACE INET Addr &addr);int accept(ACE SOCK Stream &new sap,ACE INET Addr *,ACE Time Value *);//.};53

Advanced ACE TutorialDouglas C. SchmidtACE Connection-Oriented Socket Wrapper FacadeStreaming and Addressing Classesclass ACE SOCK Stream: public ACE SOCK {public:// Trait.typedef ACE INET Addr PEER ADDR;ssize t send (const void *buf,int n);ssize t recv (void *buf,int n);ssize t send n (const void *buf,int n);ssize t sendv n (const iovec *iov,int n);ssize t recv n (void *buf, int n);int close (void);// .};Vanderbilt Universityclass ACE INET Addr: public ACE Addr{public:ACE INET Addr (u short port,const char host[]);u short get port number (void);ACE UINT 32 get ip addr (void);// .};54

Advanced ACE TutorialDouglas C. SchmidtDesign Interlude: Motivating theSocket Wrapper Facade Structure Q: Why decouple the ACE SOCK Acceptor and theACE SOCK Connector from ACE SOCK Stream? A: For the same reasons that ACE Acceptor andACE Connector are decoupled from ACE Svc Handler, e.g.,– An ACE SOCK Stream is only responsible for data tra

RTOS platforms, running on TCP/IP networks using C Examples are illustrated using freely available ADAPTIVE Communication Environment (ACE) OO framework components – Although ACE is written in C , the principles covered in this tutorial apply to