1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented...

41
U CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Meeting 8: Connection-Oriented Connection-Oriented Communication Communication

Transcript of 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented...

Page 1: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

1GWU CS 259 Brad Taylor Spring 2004

Systems Programming

Meeting 8:Meeting 8:

Connection-Oriented Connection-Oriented CommunicationCommunication

Page 2: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

2GWU CS 259 Brad Taylor Spring 2004

Objectives

• Connection-Oriented CommunicationConnection-Oriented Communication• Transmission Control Protocol / Internet Transmission Control Protocol / Internet Protocol (TCP/IP) Protocol (TCP/IP) • Client-Server Model Client-Server Model • Simple Client-Server Implementation: UICI Simple Client-Server Implementation: UICI • UNIX SocketsUNIX Sockets• Project Status Briefs (85% code review)Project Status Briefs (85% code review)• Assignment 4: due in 2 weeks, Assignment 4: due in 2 weeks, finish project finish project testingtesting this week! this week!

Page 3: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

3GWU CS 259 Brad Taylor Spring 2004

Power of Communication

• Communication very strange topic (all spent years on it)Communication very strange topic (all spent years on it)– Sounds trite, but incredible forceSounds trite, but incredible force– New ways to transmit/represent information = revolutionNew ways to transmit/represent information = revolution– Speedup = more transmission; does reception also increase? Speedup = more transmission; does reception also increase?

{D}{D}

• Examples:Examples:– BooksBooks enabled communication through time, across geography: enabled communication through time, across geography:

changed worldchanged world – RadioRadio communication over air: communication over air: changed planetchanged planet– TelephoneTelephone escape geographic tyranny, talk to anyone in world: escape geographic tyranny, talk to anyone in world:

try to find someone who hasn’t used ittry to find someone who hasn’t used it– TV, InternetTV, Internet revolutionary implication: revolutionary implication: watch CSci 259 in bedwatch CSci 259 in bed

• Can view communication as transport Can view communication as transport – Moving signal over geographyMoving signal over geography– New transport = revolution: Ships, Trains, Cars, Planes, Rockets New transport = revolution: Ships, Trains, Cars, Planes, Rockets

Big difference between no bits of information and even a fewBig difference between no bits of information and even a few

Page 4: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

4GWU CS 259 Brad Taylor Spring 2004

Power of Computer Networks

• Computer networks:Computer networks:– Send symbolic information (1’s and 0’s) between Send symbolic information (1’s and 0’s) between

“nodes”“nodes”

• Universal substrate, same plumbing supports Universal substrate, same plumbing supports many revolutions:many revolutions:– emailemail: talk to anyone in world in a different way: talk to anyone in world in a different way– newsnews: broadcast to bunch of different people: broadcast to bunch of different people– WebWeb: now even grandma uses computer: now even grandma uses computer– Implications still playing out… Implications still playing out…

01010111001A B

Page 5: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

5GWU CS 259 Brad Taylor Spring 2004

Computer NetworksCarry Symbols

• Transportation history dominated by moving thingsTransportation history dominated by moving things– Covered wagons, Trucks, Railways, Cars move people & goodsCovered wagons, Trucks, Railways, Cars move people & goods

• Networks different, move bitsNetworks different, move bits– The great invention: the The great invention: the packetpacket: encapsulates information in : encapsulates information in

opaque sequence of 1s and 0sopaque sequence of 1s and 0s

– Result: totally general, can carry any sequence of bitsResult: totally general, can carry any sequence of bits

• Information is weirdInformation is weird– RecursiveRecursive: wrap packet in another packet : wrap packet in another packet – PartitionablePartitionable: split packet arbitrarily and then reassemble: split packet arbitrarily and then reassemble– Time independentTime independent: information can flow at different rates: information can flow at different rates– Encoding independentEncoding independent: translate into another form and back : translate into another form and back – GenericGeneric: completely general error detection/correction: completely general error detection/correction

Most states, illegal to wrap a chicken in anotherMost states, illegal to wrap a chicken in another

Aren’t allowed to split up people and then reassembleAren’t allowed to split up people and then reassemble

Client view: tell A “Hello” A Network view1010111...

Each time new transport, revolutionEach time new transport, revolution

Page 6: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

6GWU CS 259 Brad Taylor Spring 2004

Example Networks

• ARPAnetARPAnet: : – First widely-used network, developed early 70s, still in useFirst widely-used network, developed early 70s, still in use– Connects large timesharing systems with leased phone lines Connects large timesharing systems with leased phone lines

cross-country cross-country – Provides mail, file transfer, remote loginProvides mail, file transfer, remote login

• UsenetUsenet::– Developed late 70s - early 80sDeveloped late 70s - early 80s– Unix systems phone each other to send mail & transfer filesUnix systems phone each other to send mail & transfer files

• Local area networks (Local area networks (LANLANs)s)– Developed early 80s to connect workstationsDeveloped early 80s to connect workstations– Ethernet most popularEthernet most popular

• InternetInternetworks: works: – Mechanisms for tying existing networks together Mechanisms for tying existing networks together

Page 7: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

7GWU CS 259 Brad Taylor Spring 2004

Networking Big Win• Allows decentralization (yet still share)Allows decentralization (yet still share)

– Rather than one big thing, build pieces and connectRather than one big thing, build pieces and connect

– Result: biggest things in the world are network-based Result: biggest things in the world are network-based (“distributed systems”): Internet, telephone system …(“distributed systems”): Internet, telephone system …

• Decentralization gives: Decentralization gives: – RobustnessRobustness: one part breaks, who cares: one part breaks, who cares– Piecemeal constructionPiecemeal construction: rather than all at once (investment $): rather than all at once (investment $)– ModularityModularity: end point internals don’t matter; just adhere to : end point internals don’t matter; just adhere to

protocol and can talkprotocol and can talk– Massive concurrencyMassive concurrency: each node doing its own thing: each node doing its own thing

• But But how to connect heterogeneous, ever-changing, how to connect heterogeneous, ever-changing, massively complex network?massively complex network?

Page 8: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

8GWU CS 259 Brad Taylor Spring 2004

A Solution: Layers• Consider networks as made of three main layers:Consider networks as made of three main layers:

– Link levelLink level: physically encode bits on “wire” (line segment): physically encode bits on “wire” (line segment)

– Network layerNetwork layer: connecting segments, addressing (locating : connecting segments, addressing (locating points on graph) and routing (navigating graph)points on graph) and routing (navigating graph)

– End-to-end layerEnd-to-end layer: make networking simple and reliable: make networking simple and reliable

0101010

ba

0101011

0 1 0 1 0 1 0 1 0 0101010

0101010

Page 9: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

9GWU CS 259 Brad Taylor Spring 2004

How Do Layers Work?• Rules:Rules:

– Layers do not look inside packetLayers do not look inside packet– If needing auxiliary information, attach header to If needing auxiliary information, attach header to

message on way down, strip on way upmessage on way down, strip on way up

– Protocol = Contract to talk to others at same levelProtocol = Contract to talk to others at same level

Application

End-to-end (TCP)

Network level (IP)

Link level (eth) eth

TCP

TCPIP

TCPIPeth eth

TCP

TCPIP

TCPIPeth

Page 10: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

10GWU CS 259 Brad Taylor Spring 2004

Why layers?• Major reason: independenceMajor reason: independence

– Layers treat each other’s headers as opaque Layers treat each other’s headers as opaque – Change lower without Change lower without changing upper changing upper

– Change upper without Change upper without changing lower changing lower

• Placement Placement – Technology evolve at different rates? Layer betweenTechnology evolve at different rates? Layer between– Functionality needed by most clients? Move downFunctionality needed by most clients? Move down– Functionality needed by some clients? Move up Functionality needed by some clients? Move up

eth

TCP UDP BLAST

TCP

AN2 ETH FDDI ATM

Page 11: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

11GWU CS 259 Brad Taylor Spring 2004

Networking Fundamentals• Networking connects Networking connects geographically separatedgeographically separated things things• Implication 1: speed of light importantImplication 1: speed of light important

– 1ft/nanosecond 1ft/nanosecond – Can’t get betterCan’t get better

• Implication 2: sharing (multiplexing)Implication 2: sharing (multiplexing)– Laying pipe very expensive: Laying pipe very expensive:

» ~10 Billion to replace wire with fiber in Britain; ~10 Billion to replace wire with fiber in Britain; » slice of radio spectrum cost 1.7 Billion at FCC auctionslice of radio spectrum cost 1.7 Billion at FCC auction

– Amortize cost by putting multiple machines on each link.Amortize cost by putting multiple machines on each link.

– Multiple users, one resource = need to multiplexMultiple users, one resource = need to multiplex– We’ve had sharing before; what’s new? We’ve had sharing before; what’s new? BlindnessBlindness

15 millisecondsSF Boston

Page 12: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

12GWU CS 259 Brad Taylor Spring 2004

Performance: Latency & Bandwidth

• Latency: how long minimum communication takes Latency: how long minimum communication takes • Bandwidth: number of bits per time unitBandwidth: number of bits per time unit

• Usual ways to minimize latency?Usual ways to minimize latency?– Caching Caching reducesreduces latency when cache hits latency when cache hits– Prefetching Prefetching hideshides latencylatency– Concurrency Concurrency toleratestolerates latency by doing something else latency by doing something else

• Save bandwidth?Save bandwidth?– Which latency trick(s) save bandwidth? Which latency trick(s) save bandwidth? – How to trade CPU for bandwidth? How to trade CPU for bandwidth? – Save both: change representationSave both: change representation

bandwidth

latency

link

Page 13: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

13GWU CS 259 Brad Taylor Spring 2004

Recursion Theme • ConstructionConstruction::

– Base case: Base case: linklink– Inductive step: Inductive step: connect linksconnect links (or networks) (or networks)

• UseUse: : encapsulateencapsulate packet in another, in another, … packet in another, in another, … – Universal transport: send message over any networkUniversal transport: send message over any network– Encapsulation: send message using another layer: wrap up, Encapsulation: send message using another layer: wrap up,

handoff, unwraphandoff, unwrap

– Big use: send new protocols across old routersBig use: send new protocols across old routers

• PresencePresence: each layer in computer system has network: each layer in computer system has network– CPU connected to disk by I/O bus, cache connected to CPU connected to disk by I/O bus, cache connected to

memory by memory bus, CPU to register by wire… memory by memory bus, CPU to register by wire…

x x

X

y

X Y X

Page 14: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

14GWU CS 259 Brad Taylor Spring 2004

Recursion: It’s Networks All the Way Down!

• Every layer in computer has three componentsEvery layer in computer has three components– ComputationComputation, , MemoryMemory, , Connection networkConnection network

• And up, too! And up, too! SocialSocial mimics mimics technicaltechnical: Network standards : Network standards bodies mimic network itselfbodies mimic network itself

Internet

LAN

100MB RAM CPU

RegisterHow fast? How many?

10M/100TB

500/50GB

1/100MB

3ns

1us

1ms

100ms

Page 15: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

15GWU CS 259 Brad Taylor Spring 2004

Connectivity Theme Variations

• Point-to-point vs one-to-all (broadcast) connectivity Point-to-point vs one-to-all (broadcast) connectivity

– Broadcast medium cheap; problem: contentionBroadcast medium cheap; problem: contention• Indirect connectivity: Indirect connectivity:

– RarelyRarely have point-to-point connection with destination have point-to-point connection with destination– UsuallyUsually messages “hop” through multiple intermediaries messages “hop” through multiple intermediaries

– RouterRouter: connect one network to another (=> internetwork): connect one network to another (=> internetwork)• No connectivity: must deal with failure constantlyNo connectivity: must deal with failure constantly

– Networks tend to be bigNetworks tend to be big– As n increases, # of dead things does also (link down)As n increases, # of dead things does also (link down)– As n increases, # of overloaded things does also (msg lost)As n increases, # of overloaded things does also (msg lost)

switch

a b

Page 16: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

16GWU CS 259 Brad Taylor Spring 2004

Synthesized Reliability Theme

Networks are unreliableNetworks are unreliable– Losses, corruptions, reorders and duplicate messagesLosses, corruptions, reorders and duplicate messages– False premise: must make lower levels perfectFalse premise: must make lower levels perfect

General approach: detect + retransmissionGeneral approach: detect + retransmission– General trickGeneral trick: something dead doesn’t respond: : something dead doesn’t respond: SoSo wait wait

“reasonable amount of time”; no response, assume dead“reasonable amount of time”; no response, assume dead– Lost messages reliabilityLost messages reliability: Send message, wait for : Send message, wait for

acknowledgement, if timeout, re-send; repeat, as neededacknowledgement, if timeout, re-send; repeat, as needed– Corruption reliabilityCorruption reliability: Use checksum to detect flipped bits; : Use checksum to detect flipped bits;

discard if doesn’t matchdiscard if doesn’t match– Duplication in time, rather than in spaceDuplication in time, rather than in space

Page 17: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

17GWU CS 259 Brad Taylor Spring 2004

• Low level functions either redundant or cheap Low level functions either redundant or cheap compared to cost of providing them where neededcompared to cost of providing them where needed– Low level incorporation: everyone must pay for itLow level incorporation: everyone must pay for it

• Useless security example:Useless security example:– Safely send credit card #: encrypt on local machine, send it, Safely send credit card #: encrypt on local machine, send it,

and end host decryptsand end host decrypts

– LAN also encrypting useless (only 1 link) LAN also encrypting useless (only 1 link)

• Harmful reliability example:Harmful reliability example:– Links try to synthesize reliability using retransmissionLinks try to synthesize reliability using retransmission– Delay introduced (send; wait; retransmit; repeat)Delay introduced (send; wait; retransmit; repeat)– If delay sensitive (voice, video) this is If delay sensitive (voice, video) this is exactly wrong thing to exactly wrong thing to

dodo! Better to drop packets and continue! Better to drop packets and continue

The End-to-End Argument

enc(m) = x x x dec(x) = m

Page 18: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

18GWU CS 259 Brad Taylor Spring 2004

Memory & Wire Duality • Every layer of computer made of three componentsEvery layer of computer made of three components

– ComputationComputation, , StorageStorage, , CommunicationCommunication

• The latter two are the same thing:The latter two are the same thing:– Storage: communicate through time (multiplexed in space)Storage: communicate through time (multiplexed in space)– Wires: communicate through space (multiplexed in time)Wires: communicate through space (multiplexed in time)

• Recursively implemented in terms of each otherRecursively implemented in terms of each other– Storage: use wire to get data from main memory into cache Storage: use wire to get data from main memory into cache

into register into CPUinto register into CPU– Wires: use memory to hold message for sending, and to catch Wires: use memory to hold message for sending, and to catch

message while receivingmessage while receiving

• Connected in terms of each otherConnected in terms of each other– Wires: Use a node to buffer and forward Wires: Use a node to buffer and forward – Memories: Use a wire to connectMemories: Use a wire to connect

Page 19: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

19GWU CS 259 Brad Taylor Spring 2004

Memory & Wire Duality (con’t)

• Reliability: both use duplicationReliability: both use duplication• Duplication in time: Duplication in time:

– Wires = timeout + resend (using memory)Wires = timeout + resend (using memory)– Memory = checkpoint + restore from backup (using wire)Memory = checkpoint + restore from backup (using wire)

• Duplicate in space: Duplicate in space: – Wires = send on multiple paths (duplicate wires)Wires = send on multiple paths (duplicate wires)– Memory = multiple copies (duplicate memory)Memory = multiple copies (duplicate memory)

• General naming issues are the same:General naming issues are the same:– Name spaces, mapping names to addresses using table, using Name spaces, mapping names to addresses using table, using

address to find objectaddress to find object– “ “/foo/bar” to a disk block using directories and inodes /foo/bar” to a disk block using directories and inodes – www.seas.gwu.edu to ip address to ethernet address using www.seas.gwu.edu to ip address to ethernet address using

various name tablesvarious name tables

Page 20: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

20GWU CS 259 Brad Taylor Spring 2004

Principles into Practice• Network layerNetwork layer

– Gets bits from one network collection end to anotherGets bits from one network collection end to another

– Uses globally unique names, routers, portable Uses globally unique names, routers, portable message abstraction; example: internet protocol (IP)message abstraction; example: internet protocol (IP)

• End-to-end layerEnd-to-end layer– Interface between applications & network some Interface between applications & network some

successful end-to-end protocols successful end-to-end protocols – Turning “best effort” into usable interface (such as Turning “best effort” into usable interface (such as

deriving TCP from first principles)deriving TCP from first principles)

a

b

c efr1

r2 r3

Page 21: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

21GWU CS 259 Brad Taylor Spring 2004

Success story #1: UDP

User Datagram Protocol: best-effort, process-to-processUser Datagram Protocol: best-effort, process-to-process– Lives on top of IP: adds corruption detection and “ports” so Lives on top of IP: adds corruption detection and “ports” so

packets can be addressed to a process on hostpackets can be addressed to a process on host– Many header fields are hiddenMany header fields are hidden

UDP

IP

data cksum src portdst port

Hdr cksumsrc IP addrdst IP addr

Host: IP addr = 18.26.0.1

Port 1028

Port 92Port 18

Page 22: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

22GWU CS 259 Brad Taylor Spring 2004

Success story #2: TCP

Transmission control protocolTransmission control protocol– Reliable, in-order, process-to-process, two-way byte streamReliable, in-order, process-to-process, two-way byte stream

Like UDP: Like UDP: – Layered on top of IP; adds ports and data checksumsLayered on top of IP; adds ports and data checksums

Unlike UDP:Unlike UDP:– Connection basedConnection based– Recovers from packet loss, duplication, corruption, reorderingRecovers from packet loss, duplication, corruption, reordering– ““how????” from first principleshow????” from first principles

TCP

IP

Page 23: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

23GWU CS 259 Brad Taylor Spring 2004

Lost packets

• Causes:Causes:– Traffic burst causes router buffers to overflowTraffic burst causes router buffers to overflow– Link corrupts packet (wireless up to 40% packet Link corrupts packet (wireless up to 40% packet

loss)loss)– How to fix?How to fix?

sender receiver

time

message

Page 24: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

24GWU CS 259 Brad Taylor Spring 2004

Lost acks

What will the result be?What will the result be?

sender receiver

time

M

acksender

timout

Page 25: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

25GWU CS 259 Brad Taylor Spring 2004

Delayed acks = Packet Duplication

Possible causes: Possible causes: – ““congestion” in the network that delays packetcongestion” in the network that delays packet– a too-short timeout (how big should it be anyway?)a too-short timeout (how big should it be anyway?)

receiverM

ack

sender

timout

M

Page 26: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

26GWU CS 259 Brad Taylor Spring 2004

Connection Setup: Three Way Handshake

TCP is a two-way (duplex) pipeTCP is a two-way (duplex) pipe– Different sequence number for each directionDifferent sequence number for each direction– Asymetric open: server does a passive “listen,” Asymetric open: server does a passive “listen,”

client does an active “open” (sends first message)client does an active “open” (sends first message)

sender receiver

(ack x, seq # y)

(open, seq # x)

(ack y)

Page 27: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

27GWU CS 259 Brad Taylor Spring 2004

The two army problem

– C can beat either A or B, but not both.C can beat either A or B, but not both.– A and B want to agree on a time to simultaneously attackA and B want to agree on a time to simultaneously attack– Also: The Byzantine Generals Problem Also: The Byzantine Generals Problem

C

A B

Page 28: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

28GWU CS 259 Brad Taylor Spring 2004

• Addressing: identifying receiversAddressing: identifying receivers– IP = host-to-host: every host has a unique IP addressIP = host-to-host: every host has a unique IP address– UDP & TCP = process-to-process: extend IP with a port UDP & TCP = process-to-process: extend IP with a port

that is coupled to a process within a hostthat is coupled to a process within a host– Telephone: “host-to-host”: every connection point Telephone: “host-to-host”: every connection point

associated with a unique phone number associated with a unique phone number

• Connection model:Connection model:– IP, UDP, Ethernet: IP, UDP, Ethernet: connectionlessconnectionless: Send packet: Send packet– Telephone, ATM, TCP: Telephone, ATM, TCP: connection-basedconnection-based: Explicitly set : Explicitly set

up connection before sending data; tear down up connection before sending data; tear down connection when done (richer service models easier)connection when done (richer service models easier)

• Data delivery model: once data entrusted to Data delivery model: once data entrusted to protocol, what guarantees are made? protocol, what guarantees are made?

Protocol: Naming, Setup & Guarantees

Page 29: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

29GWU CS 259 Brad Taylor Spring 2004

Two Connection Models• ConnectionlessConnectionless (or “datagram”): (or “datagram”):

– Packets contain enough information so routers can Packets contain enough information so routers can decide how to get it to its final destinationdecide how to get it to its final destination

• Connection-orientedConnection-oriented (or “virtual circuit”) (or “virtual circuit”)– Connection between two nodes first set up Connection between two nodes first set up – Label it (called virtual circuit identifier: VCI)Label it (called virtual circuit identifier: VCI)– All packets carry labelAll packets carry label

BAb b

C

BA1 1

C

1

Page 30: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

30GWU CS 259 Brad Taylor Spring 2004

Data Delivery Models• Best-effort:Best-effort:

– IPIP: packets can be lost, delayed & packet data corrupted: packets can be lost, delayed & packet data corrupted– UDPUDP: layers corruption detection on top of IP: layers corruption detection on top of IP– EthernetEthernet: may lose packets, detects corruption: may lose packets, detects corruption– ATMATM: can lose packets, detects corruption & makes reordering : can lose packets, detects corruption & makes reordering

less likelyless likely

• TCPTCP: Reliable, in-order byte stream: Reliable, in-order byte stream– two-way byte stream; prevents: loss, duplication, corruption, two-way byte stream; prevents: loss, duplication, corruption,

reorderreorder

• Mostly reliable, quality-of-service: Mostly reliable, quality-of-service: telephonetelephone– two-way voice service with small end-to-end delaystwo-way voice service with small end-to-end delays– guarantees accepted calls will run to completionguarantees accepted calls will run to completion– easier to build on ATM than non-connection basedeasier to build on ATM than non-connection based

Page 31: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

31GWU CS 259 Brad Taylor Spring 2004

Client-Server Model

• Many network communication Many network communication types use: mail, ftp, telnet, rlogin, types use: mail, ftp, telnet, rlogin, http, and nfshttp, and nfs• Server Server waitswaits for requests for requests • Client Client requestsrequests service from server service from server• Communication endpoint specified Communication endpoint specified by host address and port numberby host address and port number• Port numbers differentiate Port numbers differentiate communication channels; standard communication channels; standard port numbers allow clients to request port numbers allow clients to request services; for example: services; for example: mail: 25 mail: 25 ftp: 21 ftp: 21 telnet: 23 telnet: 23 rlogin 513 rlogin 513 http: 80 http: 80 nfs: 2049 nfs: 2049

Page 32: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

32GWU CS 259 Brad Taylor Spring 2004

Connection-Oriented Communication

• Client sets up a connection using the Client sets up a connection using the Server's well-known port number Server's well-known port number

• Then communicates over a private Then communicates over a private communications channel communications channel

Page 33: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

33GWU CS 259 Brad Taylor Spring 2004

Connection-Oriented Protocol

• Server waits for client Server waits for client request monitoring request monitoring communication communication endpoint whose endpoint whose address is known to address is known to clientsclients

• When client request When client request arrives, server arrives, server creates new creates new communication communication endpoint to handle endpoint to handle two-way symmetric two-way symmetric communication with communication with clientclient

Page 34: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

34GWU CS 259 Brad Taylor Spring 2004

UICI: Simple Connection-Oriented Client-Server

Implementation

• ServerServer::– Assign Assign file descriptorfile descriptor (fd) to (fd) to portport for listening for listening – Wait for Wait for connection requestconnection request on that fd on that fd – Return communication file descriptor when request comesReturn communication file descriptor when request comes– Handles connection by reading or writing, using the Handles connection by reading or writing, using the

communication file descriptor communication file descriptor – Requests may be handled serially, or forking a child while the Requests may be handled serially, or forking a child while the

parent is waiting for another request parent is waiting for another request

• ClientClient::– Request connection from particular port on a particular host Request connection from particular port on a particular host – If successful, returns a file descriptor for communication If successful, returns a file descriptor for communication – Communicates by doing reads and writes on this file Communicates by doing reads and writes on this file

descriptor descriptor

Page 35: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

35GWU CS 259 Brad Taylor Spring 2004

UICI: Client-Server Interaction

Page 36: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

36GWU CS 259 Brad Taylor Spring 2004

Mapping UICI to Sockets

• UICI UICI functions and UNIX functions and UNIX SocketSocket functions:functions:– u_openu_open => { => {socket, bind, listensocket, bind, listen}}– u_acceptu_accept => { => {acceptaccept}}– u_connectu_connect => { => {socket, connectsocket, connect}}– u_readu_read => { => {readread}}– u_writeu_write => { => {writewrite}}

Page 37: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

37GWU CS 259 Brad Taylor Spring 2004

Socket Functions

• UICI UICI functions and UNIX functions and UNIX SocketSocket functions :functions :– socket socket creates a file descriptor creates a file descriptor – bind bind associates a file descriptor with a port associates a file descriptor with a port

and machine and machine – listen listen sets up buffers sets up buffers – accept accept waits for a connection request waits for a connection request – connect connect requests a connection to a server requests a connection to a server

Page 38: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

38GWU CS 259 Brad Taylor Spring 2004

TCP/Socket Example: Bare Minimum Client/Server

• ServerServer::– Creates a server socket bound to a fixed Creates a server socket bound to a fixed

port (12345)port (12345)– Receives a message from a client and Receives a message from a client and

displays itdisplays it• ClientClient::

– Creates a client socketCreates a client socket– Repeatedly sends the  message "Hi" out Repeatedly sends the  message "Hi" out

of this socket to the server of this socket to the server

Page 39: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

39GWU CS 259 Brad Taylor Spring 2004

TCP Minimum: tcpServer.c

#include "def"#include "def"

main()main()

{{

int sd, psd;int sd, psd;

struct sockaddr_in name;struct sockaddr_in name;

char buf[1024];char buf[1024];

int cc;int cc;

sd = socket sd = socket (AF_INET,SOCK_STREAM,0);(AF_INET,SOCK_STREAM,0);

name.sin_family = AF_INET;name.sin_family = AF_INET;

name.sin_addr.s_addr = name.sin_addr.s_addr = htonl(INADDR_ANY);htonl(INADDR_ANY);

name.sin_port = htons(12345);name.sin_port = htons(12345);

bind( sd, (SA *) &name, bind( sd, (SA *) &name, sizeof(name) );sizeof(name) );

listen(sd,1);listen(sd,1); psd = accept(sd, 0, 0);psd = accept(sd, 0, 0); close(sd);close(sd); for(;;) {for(;;) {

cc=recv(psd,buf,sizeof(buf), 0) cc=recv(psd,buf,sizeof(buf), 0) ;;

if (cc == 0) exit (0);if (cc == 0) exit (0); buf[cc] = NULL;buf[cc] = NULL; printf("message printf("message

received: %s\n", buf);received: %s\n", buf); }}}}

Page 40: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

40GWU CS 259 Brad Taylor Spring 2004

TCP Minimum: tcpClient.c

main(argc, argv )main(argc, argv )

int argc;int argc;

char *argv[];char *argv[];

{{

intint sd;sd;

structstruct sockaddr_in server;sockaddr_in server;

struct hostent *hp, struct hostent *hp, *gethostbyname();*gethostbyname();

sd = socket sd = socket (AF_INET,SOCK_STREAM,0);(AF_INET,SOCK_STREAM,0);

server.sin_family = AF_INET;server.sin_family = AF_INET;

hp = gethostbyname(argv[1]);hp = gethostbyname(argv[1]);bcopy ( hp->h_addr, bcopy ( hp->h_addr, &(server.sin_addr.s_addr), hp-&(server.sin_addr.s_addr), hp->h_length);>h_length);server.sin_port = htons(12345);server.sin_port = htons(12345);connect(sd, (SA *) &server, connect(sd, (SA *) &server, sizeof(server));sizeof(server));

for (;;) {for (;;) { send(sd, "HI", 2, 0 );send(sd, "HI", 2, 0 );

printf("sent HI\n");printf("sent HI\n"); sleep(2);sleep(2); }}}}

Page 41: 1GWU CS 259 Brad Taylor Spring 2004 Systems Programming Meeting 8: Connection-Oriented Communication.

41GWU CS 259 Brad Taylor Spring 2004

Project Status Report

Nate: GLIB Loop Example …Nate: GLIB Loop Example …

Group I: Dan, Ricardo & Kamal: “Wire Socket”Group I: Dan, Ricardo & Kamal: “Wire Socket”

Group II: Clayton, Jason: “Named Pipes”Group II: Clayton, Jason: “Named Pipes”

Group III: Brooke, Nush, Ram: “Shared Memory, Semaphores & Futexs”Group III: Brooke, Nush, Ram: “Shared Memory, Semaphores & Futexs”

Integration: Nate & BradIntegration: Nate & Brad

Issues to discuss:Issues to discuss:Code Review for Each GroupCode Review for Each GroupError checkingError checkingRough draft code submission for integration reviewRough draft code submission for integration reviewFurther Guidance, QuestionsFurther Guidance, Questions