Non-Persistent HTTP: Response time definition of RTT: time for a small packet to travel from client to server and back. initiate TCP response time: connection } one RTT to initiate TCP RTT connection request file } one RTT for HTTP request time to RTT transmit and first few bytes of HTTP file response to return file received } file transmission time total = 2RTT+transmit time time time Application 2-25
Persistent HTTP non-persistent HTTP issues: persistent HTTP } requires 2 RTTs per object } server leaves connection open after sending response } OS overhead for each TCP connection } subsequent HTTP messages between same client/server sent over open connection } client sends requests as soon as it encounters a referenced object } as little as one RTT for all the referenced objects Application 2-26
Advantage of non-persistent HTTP non-persistent HTTP: } browsers can open parallel TCP connections to fetch referenced objects “at the same time” } Has advantages and disadvantages Application 2-27
HTTP request message http://www-net.cs.umass.edu:8080/index.html } two types of HTTP messages: request , response } HTTP request message: } ASCII (human-readable format) carriage return character line-feed character request line (GET, POST, GET /index.html HTTP/1.1\r\n HEAD commands) Host: www-net.cs.umass.edu\r\n User-Agent: Firefox/3.6.10\r\n Accept: text/html,application/xhtml+xml\r\n header Accept-Language: en-us,en;q=0.5\r\n lines Accept-Encoding: gzip,deflate\r\n Accept-Charset: ISO-8859-1,utf-8;q=0.7\r\n carriage return, Keep-Alive: 115\r\n Connection: keep-alive\r\n line feed at start \r\n of line indicates end of header lines Application 2-28
HTTP request message: general format request line header lines body Application 2-29
A simple test… **** } $ nc –l 12345 } Point your browser to http://127.0.0.1:12345/testme } If your user-agent looks strange and you curious to know why, read this: } http://webaim.org/blog/user-agent-string-history/ 30 2: Application Layer
Uploading form input POST method: } web page often includes form input } input is uploaded to server in entity body URL method: } uses GET method } input is uploaded in URL field of request line: www.somesite.com/animalsearch?monkeys&banana www.example.com/animalsearch.php?name=monkeys&age=10 Application 2-31
Method types HTTP/1.0 HTTP/1.1 } GET } GET, POST, HEAD } POST } PUT } uploads file in entity body to } HEAD path specified in URL field } asks server to leave requested } DELETE object out of response } deletes file specified in the URL field Application 2-32
HTTP response message status line (protocol status code HTTP/1.1 200 OK\r\n status phrase) Date: Sun, 26 Sep 2010 20:09:20 GMT\r\n Server: Apache/2.0.52 (CentOS)\r\n Last-Modified: Tue, 30 Oct 2007 17:00:02 GMT\r\n ETag: "17dc6-a5c-bf716880"\r\n header Accept-Ranges: bytes\r\n lines Content-Length: 2652\r\n Keep-Alive: timeout=10, max=100\r\n Connection: Keep-Alive\r\n Content-Type: text/html; charset=ISO-8859-1\r\n \r\n data data data data data ... data, e.g., requested HTML file Application 2-33
HTTP response status codes v status code appears in 1st line in server->client response message. v some sample codes: 200 OK } request succeeded, requested object later in this msg 301 Moved Permanently } requested object moved, new location specified later in this msg (Location:) 400 Bad Request } request msg not understood by server 404 Not Found } requested document not found on this server 505 HTTP Version Not Supported Application 2-34
Trying out HTTP (client side) for yourself 1. Telnet to your favorite Web server: telnet www.uga.edu 80 opens TCP connection to port 80 (default HTTP server port) at cis.poly.edu. anything typed in sent to port 80 at cis.poly.edu 2. type in a GET HTTP request: by typing this in (hit carriage return twice), you send GET /profile/mission HTTP/1.1 this minimal (but complete) Host: www.uga.edu GET request to HTTP server 3. look at response message sent by HTTP server! (or use wireshark!) Application 2-35
User-server state: cookies many Web sites use cookies example: four components: } Susan always access Internet 1) cookie header line of HTTP from PC response message 2) cookie header line in HTTP } visits specific e-commerce request message site for first time 3) cookie file kept on user’s host, } when initial HTTP requests managed by user’s browser arrives at site, site creates: 4) back-end database at Web site } unique ID } entry in backend database for ID Application 2-36
Cookies: keeping “state” (cont.) client server ebay 8734 usual http request msg Amazon server creates ID cookie file usual http response 1678 for user create Set-cookie: 1678 entry ebay 8734 amazon 1678 usual http request msg cookie- access cookie: 1678 specific backend usual http response msg one week later: action database access ebay 8734 usual http request msg cookie- amazon 1678 cookie: 1678 specific usual http response msg action Application 2-37
Cookies (continued) aside cookies and privacy: what cookies can bring: v cookies permit sites to } authorization learn a lot about you } shopping carts v you may supply name } recommendations and e-mail to sites } user session state (Web e- mail) how to keep “state”: v protocol endpoints: maintain state at sender/receiver over multiple transactions v cookies: http messages carry state Application 2-38
Cookies and Privacy } Two types of cookies } Session cookies } Permanent cookies (tracking cookies) } Third-party cookies (see http://tools.ietf.org/html/rfc2965) } You visit www.example.com, which contains a banner from ads.clicks- for-me.net } in simple terms ads.clicks-for-me.net is third-party because it does not match the domain showed on the URL bar } third-party sites should be denied setting or reading cookies } The browser allows ads.clicks-for-me.net to drop a third-party cookie } Then you visit www.another-example.com , which also loads ads from ads.clicks-for-me.net } ads.clicks-for-me.net can track the fact that you visited both www.example.com and www.another-example.com !!! 39 2: Application Layer
Cookies and Security } Authentication Cookies can be stolen } An attacker may be able to “sniff” your authentication cookies } The attacker will be able to login as you on a website (e.g., Facebook, Twitter, etc…) } See FireSheep for a concrete example! } http://codebutler.com/firesheep 40 2: Application Layer
Session IDs } Cookies are not the only way you can keep state } Session IDs are commonly used by web applications } http://example.com/index.php?user_id=0F4C26A1&topic=networking } What are the main difference between cookies and Session IDs? } Session IDs are typically passed in the URL (added to web app links) } Cookies are passed through HTTP req/resp headers } Cookies are stored in the browser’s cache and have an expiration date } Session IDs are volatile: never stored, only used until end of session 41 2: Application Layer
Web caches (proxy server) Goal: satisfy client request without involving origin server origin } user sets browser: Web server accesses via cache Proxy } browser sends all HTTP server requests to cache client } object in cache: cache returns object } else cache requests object from origin server, then returns object to client client origin server Application 2-42
More about Web caching } cache acts as both client and why Web caching? server } reduce response time for } Splits the TCP connection! client request } typically cache is installed by } reduce traffic on an ISP (university, company, institution’s access link. residential ISP) } Internet dense with caches: enables “poor” content providers to effectively deliver content (but so does P2P file sharing) Caching in HTTP http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html Application 2-43
Caching example origin assumptions servers } average object size = 1M bits public } avg. request rate from institution’s Internet browsers to origin servers = 15/sec } delay from “Internet router” to any origin server and back to router = 15 Mbps 2 sec access link consequences institutional network 100 Mbps LAN } utilization on LAN = 15% } utilization on access link = 100% } total delay = Internet delay + access delay + LAN delay institutional = 2 sec + minutes + milliseconds cache Due to traffic intensity = 1 on the access link Application 2-44
Caching example (cont) origin possible solution servers } increase bandwidth of access link public to, say, 100 Mbps Internet consequence } utilization on LAN = 15% } utilization on access link = 15% 100 Mbps access link } Total delay = Internet delay + access delay + LAN delay institutional network 100 Mbps LAN = 2 sec + msecs + msecs } often a costly upgrade institutional cache Application 2-45
Caching example (cont) origin possible solution: servers } install cache public Internet consequence } suppose hit rate is 0.4 } 40% requests will be satisfied 15 Mbps almost immediately access link } 60% requests satisfied by origin server institutional network } utilization of access link reduced 100 Mbps LAN to 60%, resulting in negligible delays (say 10 msec) } total avg delay = Internet delay + access delay + LAN delay = institutional 0.6*(2.01) secs + cache 0.4*milliseconds < 1.4 secs Application 2-46
Conditional GET cache server HTTP request msg object If-modified-since: <date> } Goal: don’t send object if cache not has up-to-date cached version modified before HTTP response } cache: specify date of cached HTTP/1.0 <date> copy in HTTP request 304 Not Modified If-modified-since: <date> HTTP request msg } server: response contains no If-modified-since: <date> object if cached copy is up-to- object date: modified HTTP response after HTTP/1.0 304 Not Modified HTTP/1.0 200 OK <date> <data> In reality, cache entry validation and eviction policies are quite complex http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13 Application 2-47
HTTP Pipelining and Range } Pipelining } The client sends multiple HTTP request without waiting for server response } The server sends the response one after the other } Range } HTTP allows downloading pieces of objects } Example: } 10MB image to be downloaded } We can open 10 different TCP connection and send 10 HTTP requests in parallel } Download 1MB of data from each connection and stitch them back together 48 2: Application Layer
FTP: the file transfer protocol file transfer FTP FTP FTP user client server interface user remote file at host local file system system } transfer file to/from remote host } client/server model } client: side that initiates transfer (either to/from remote) } server: remote host } ftp: RFC 959 } ftp server: port 21 Application 2-49
FTP: separate control, data connections TCP control connection port 21 } FTP client contacts FTP server at port 21, TCP is transport protocol } client authorized over control TCP data connection FTP FTP port 20 connection client server } client browses remote directory by sending commands over control v server opens another TCP connection. data connection to transfer } when server receives file transfer another file. command, server opens 2 nd TCP v control connection: “out of connection (for file) to client band” } after transferring one file, server v FTP server maintains “state”: closes data connection. current directory, earlier authentication Application 2-50
FTP: separate control, data connections TCP control connection port 21 } Active FTP FTP server contacts client from TCP TCP data connection FTP src-port 20 to negotiated dst-port FTP from serv port 20 client server TCP control connection port 21 } Passive FTP client contacts FTP server at negotiated TCP dst-port TCP data connection FTP FTP to negotiated serv port client server When is Passive FTP useful? Application 2-51
FTP commands, responses sample commands: sample return codes } status code and phrase (as in } sent as ASCII text over control channel HTTP) } USER username } 331 Username OK, password required } PASS password } 125 data connection } LIST return list of file in current already open; transfer directory starting } RETR filename retrieves } 425 Can’t open data (gets) file connection } STOR filename stores (puts) } 452 Error writing file file onto remote host Application 2-52
Electronic Mail outgoing message queue user mailbox Three major components: user agent } user agents mail } mail servers user server agent } simple mail transfer protocol: SMTP SMTP mail server user User Agent agent SMTP } a.k.a. “mail reader” SMTP } composing, editing, reading mail user messages mail agent server } e.g., Eudora, Outlook, elm, Mozilla Thunderbird user } outgoing, incoming messages agent stored on server user agent Application 2-53
Electronic Mail: mail servers user Mail Servers agent } mailbox contains incoming mail user server messages for user agent } message queue of outgoing (to be SMTP mail sent) mail messages server user } SMTP protocol between mail agent SMTP servers to send email messages SMTP } client: sending mail server user mail } “server”: receiving mail server agent server user agent user agent Application 2-54
Electronic Mail: SMTP [RFC 2821] } uses TCP to reliably transfer email message from client to server, port 25 } direct transfer: sending server to receiving server } three phases of transfer } handshaking (greeting) } transfer of messages } closure } command/response interaction } commands: ASCII text } response: status code and phrase } messages must be in 7-bit ASCII Application 2-55
Scenario: Alice sends message to Bob 4) SMTP client sends Alice’s 1) Alice uses UA to compose message over the TCP message and “to” connection bob@someschool.edu 5) Bob’s mail server places the 2) Alice’s UA sends message to her message in Bob’s mailbox mail server; message placed in message queue 6) Bob invokes his user agent to read message 3) Client side of SMTP opens TCP connection with Bob’s mail server 1 mail mail user server server user agent 2 6 3 agent 4 5 Application 2-56
Sample SMTP interaction S: 220 hamburger.edu C: HELO crepes.fr S: 250 Hello crepes.fr, pleased to meet you C: MAIL FROM: <alice@crepes.fr> S: 250 alice@crepes.fr... Sender ok C: RCPT TO: <bob@hamburger.edu> S: 250 bob@hamburger.edu ... Recipient ok C: DATA S: 354 Enter mail, end with "." on a line by itself C: From: Alice C: To: Bob C: Subject: Quick question C: Do you like ketchup? C: . S: 250 Message accepted for delivery C: QUIT S: 221 hamburger.edu closing connection Application 2-57
Try SMTP interaction for yourself: } telnet servername 25 } see 220 reply from server } enter HELO, MAIL FROM, RCPT TO, DATA, QUIT commands above lets you send email without using email client (reader) Application 2-58
Concrete example*** $ dig +short -t MX uga.edu 10 1282373658.mail.outlook.com. $ dig +short -x 198.137.20.113 h198-137-20-113.paws.uga.edu. $ telnet 1282373658.mail.outlook.com. 25 Trying 216.32.181.178... Connected to 1282373658.mail.outlook.com. Escape character is '^]'. 220 CH1EHSMHS014.bigfish.com Microsoft ESMTP MAIL Service ready at Tue, 29 Jan 2013 15:20:08 HELO h198-137-20-113.paws.uga.edu 250 CH1EHSMHS014.bigfish.com Hello [128.192.4.39] MAIL FROM: <perdisci@cs.uga.edu> 250 2.1.0 Sender OK RCPT TO: <perdisci@uga.edu> 250 2.1.5 Recipient OK DATA 354 Start mail input; end with <CRLF>.<CRLF> From: Roberto <perdisci@cs.uga.edu> To: Rob <perdisci@uga.edu> Subject: Quick question Do you like ketchup? . 250 2.6.0 <….ehs.local> [InternalId=21919093] Queued mail for delivery QUIT 221 2.0.0 Service closing transmission channel 59 2: Application Layer Connection closed by foreign host.
Mail message format SMTP: protocol for exchanging email msgs header RFC 822: standard for text message blank format: line } header lines, e.g., } To: } From: body } Subject: different from SMTP commands ! } body } the “message”, ASCII characters only Application 2-60
SMTP: final words } SMTP uses persistent connections comparison with HTTP: } SMTP requires message (header & } HTTP: pull body) to be in 7-bit ASCII } SMTP: push } SMTP server uses CRLF.CRLF to determine end of message } both have ASCII command/ response interaction, status codes } HTTP: each object encapsulated in its own response msg } SMTP: multiple objects sent in multipart msg Application 2-61
Mail access protocols SMTP SMTP access user user protocol agent agent receiver’s mail sender’s mail server server } SMTP: delivery/storage to receiver’s server } mail access protocol: retrieval from server } POP: Post Office Protocol [RFC 1939] } authorization (agent <-->server) and download } IMAP: Internet Mail Access Protocol [RFC 1730] } more features (more complex) } manipulation of stored msgs on server Yahoo! Mail, etc. } HTTP: gmail, Hotmail, Application 2-62
POP3 protocol S: +OK POP3 server ready C: user bob authorization phase S: +OK C: pass hungry } client commands: S: +OK user successfully logged on } user: declare username C: list } pass: password S: 1 498 } server responses S: 2 912 } +OK S: . C: retr 1 } -ERR S: <message 1 contents> transaction phase, client: S: . } list: list message numbers C: dele 1 C: retr 2 } retr: retrieve message by S: <message 1 contents> number S: . } dele: delete C: dele 2 } quit C: quit S: +OK POP3 server signing off Application 2-63
POP3 (more) and IMAP more about POP3 IMAP } previous example uses } keeps all messages in one “download and delete” place: at server mode. } allows user to organize } Bob cannot re-read e-mail messages in folders if he changes client } keeps user state across } “download-and-keep”: sessions: copies of messages on } names of folders and different clients mappings between message IDs and folder name } POP3 is stateless across sessions Application 2-64
Chapter 2: Application layer } 2.1 Principles of network applications } 2.6 P2P applications } 2.2 Web and HTTP } 2.7 Socket programming with TCP } 2.3 FTP } 2.8 Socket programming } 2.4 Electronic Mail with UDP } SMTP , POP3, IMAP } 2.5 DNS Application 2-65
DNS: Domain Name System people: many identifiers: Domain Name System: } SSN, name, passport # Internet hosts, routers: } distributed database implemented in hierarchy of many name servers } IP address (32 bit) - used for } application-layer protocol host, addressing datagrams routers, name servers to } “name”, e.g., ww.yahoo.com - communicate to resolve names used by humans (address/name translation) Q: map between IP address } note: core Internet function, and name, and vice versa ? implemented as application-layer protocol } complexity at network’s “edge” Application 2-66
DNS Why not centralize DNS? DNS services } single point of failure } hostname to IP address translation } traffic volume } host aliasing } distant centralized database } Canonical, alias names } maintenance } mail server aliasing } load distribution doesn’t scale! } replicated Web servers: set of IP addresses for one canonical name Application 2-67
Distributed, Hierarchical Database Root DNS Servers org DNS servers edu DNS servers com DNS servers poly.edu umass.edu pbs.org yahoo.com amazon.com DNS servers DNS servers DNS servers DNS servers DNS servers client wants IP for www.amazon.com; 1 st approx: } client queries a root server to find com DNS server } client queries com DNS server to get amazon.com DNS server } client queries amazon.com DNS server to get IP address for www.amazon.com Application 2-68
DNS: Root name servers http://www.internetsociety.org/sites/default/files/DNS%20Root%20Name%20Servers%20Frequently%20Asked%20Questions.doc.pdf } contacted by local name server that can not resolve name } root name server: } contacts authoritative name server if name mapping not known } gets mapping } returns mapping to local name server a Verisign, Dulles, VA c Cogent, Herndon, VA (also LA) k RIPE London (also 16 other locations) d U Maryland College Park, MD g US DoD Vienna, VA h ARL Aberdeen, MD i Autonomica, Stockholm (plus j Verisign, ( 21 locations) 28 other locations) m WIDE Tokyo (also Seoul, Paris, SF) e NASA Mt View, CA f Internet Software C. Palo Alto, CA (and 36 other locations) 13 root name servers worldwide b USC-ISI Marina del Rey, CA l ICANN Los Angeles, CA Application 2-69
TLD and Authoritative Servers Top-level domain (TLD) servers: } responsible for com, org, net, edu, aero, jobs, museums, and all top-level country domains, e.g.: uk, fr, ca, jp. } Network Solutions maintains servers for com TLD } Educause for edu TLD Authoritative DNS servers: } organization’s DNS servers, providing authoritative hostname to IP mappings for organization’s servers (e.g., Web, mail). } can be maintained by organization or service provider Application 2-70
Local Name Server } does not strictly belong to hierarchy } each ISP (residential ISP , company, university) has one. } also called “default name server” } when host makes DNS query, query is sent to its local DNS server } acts as proxy, forwards query into hierarchy Application 2-71
DNS name *** root DNS server resolution example 2 3 } host at cis.poly.edu TLD DNS server Local 4 wants IP address for DNS gaia.cs.umass.edu 5 iterated query: Query for gaia.cs.umass.edu v contacted server 6 7 1 8 replies with name of server to contact authoritative DNS server v “I don’t know this dns.cs.umass.edu name, but ask this server” gaia.cs.umass.edu Application 2-72
DNS name *** resolution example root DNS server recursive query: 2 3 v puts burden of name 6 7 resolution on TLD DNS server contacted name server local DNS server v heavy load? 4 5 dns.poly.edu 1 8 authoritative DNS server dns.cs.umass.edu requesting host cis.poly.edu gaia.cs.umass.edu Application 2-73
DNS: caching and updating records } once (any) name server learns mapping, it caches mapping } cache entries timeout (disappear) after some time } TLD servers typically cached in local name servers } Thus root name servers not often visited Application 2-74
DNS records DNS: distributed db storing resource records (RR) RR format: (name, value, type, ttl) Type=A Type=CNAME § name is hostname § name is alias name for some “canonical” (the real) name § value is IP address § www.ibm.com is really Type=NS servereast.backup2.ibm.com } name is domain (e.g. foo.com) § value is canonical name } value is hostname of authoritative name server for Type=MX this domain § value is name of mailserver associated with name Application 2-75
DNS protocol, messages DNS protocol : query and reply messages, both with same message format msg header v identification: 16 bit # for query, reply to query uses same # v flags: § query or reply § recursion desired § recursion available § reply is authoritative Application 2-76
DNS protocol, messages Name, type fields for a query RRs in response to query records for authoritative servers additional “helpful” info that may be used Application 2-77
Inserting records into DNS } example: new startup “Network Utopia” } register name networkuptopia.com at DNS registrar (e.g., Network Solutions) } provide names, IP addresses of authoritative name server (primary and secondary) } registrar inserts two RRs into com TLD server: (networkutopia.com, dns1.networkutopia.com, NS) (dns1.networkutopia.com, 212.212.212.1, A) } create authoritative server Type A record for www.networkuptopia.com; Type MX record for networkutopia.com } How do people get IP address of your Web site? Application 2-78
DNS Poisoning } DNS uses UDP } Source IP address can be spoofed } Responses are accepted with a “First Comes First Wins” policy, subsequent } Only check is on TXID local DNS server } What consequences? dns.poly.edu authoritative DNS server dns.cs.umass.edu requesting host cis.poly.edu 79 2: Application Layer gaia.cs.umass.edu
DNSSEC } DNS “patches” } Port randomization } 0x20-Bit encoding } Better solution: DNSSEC } Responses are digitally signed } They can be verified by following a chain of trust anchored at the roots } Not yet fully deployed 80 2: Application Layer
Chapter 2: Application layer 2.1 Principles of network applications 2.6 P2P applications 2.2 Web and HTTP 2.7 Socket programming with TCP 2.3 FTP 2.8 Socket programming with 2.4 Electronic Mail UDP } SMTP , POP3, IMAP 2.5 DNS Application 2-81
Pure P2P architecture } no always-on server } arbitrary end systems directly communicate peer-peer } peers are intermittently connected and change IP addresses Applications: } file distribution } searching for information } case Study: Skype Application 2-82
Distributed Hash Table (DHT) } Problem: } Build a simple DB that can store (key, value) pairs } key: ss number; value: human name } key: file name; value: IP address of peers that have file } Clients can provide a key, and get the value from DB } Centralized solution is trivial (e.g., Napster) } DHT: distributed P2P database } No central authority } Data distributed across very large number of (unreliable) nodes } database has (key, value) pairs; } peers query DB with key } DB returns values that match the key } peers can also insert (key, value) pairs Application 2-83
DHT Identifiers } assign integer identifier to each peer in range [0,2 n -1]. } Each identifier can be represented by n bits. } require each key to be an integer in same range. } to get integer keys, hash original key. } e.g., key = h(“Led Zeppelin IV”) } this is why they call it a distributed “hash” table Application 2-84
How to assign keys to peers? } central issue: } assigning (key, value) pairs to peers. } rule: assign key to the peer that has the closest ID. } convention in lecture: closest is the immediate successor of the key. } e.g.,: n=4; peers: 1,3,4,5,8,10,12,15; } key = 13, then successor peer = 15 } key = 15, then successor peer = 15 Application 2-85
Circular DHT (1) 1 3 15 4 12 5 10 8 } each peer only aware of immediate successor and predecessor. } “overlay network” Application 2-86
Circular DHT (2) *** 0001 O(N) messages Who’s resp on avg to resolve for key 1110 ? I am query, when there 0011 are N peers 1111 1110 0100 1110 1110 1100 0101 1110 1110 Define closest 1110 1010 as closest 1000 successor Application 2-87
Circular DHT with Shortcuts 1 Who’s resp for key 1110? 3 15 4 12 5 10 8 } each peer keeps track of IP addresses of predecessor, successor, short cuts. } reduced from 6 to 2 messages. } possible to design shortcuts so O(log N) neighbors, O(log N) messages in query Application 2-88
Peer Churn 1 v To handle peer churn, require each peer to know the IP 3 15 address of its two successors. v Each peer periodically pings its 4 two successors to see if they are still alive . 12 5 10 8 } peer 5 abruptly leaves } Peer 4 detects; makes 8 its immediate successor; asks 8 who its immediate successor is; makes 8’s immediate successor its second successor. } What if peer 13 wants to join? Application 2-89
P2P Case study: Skype Skype clients (SC) } inherently P2P: pairs of users communicate. } proprietary application- Skype layer protocol (inferred via Supernode login server reverse engineering) (SN) } hierarchical overlay with SNs } Index maps usernames to IP addresses; distributed over SNs Application 2-90
Peers as relays } problem when both Alice and Bob are behind “NATs”. } NAT prevents an outside peer from initiating a call to insider peer } solution: } using Alice’s and Bob’s SNs, relay is chosen } each peer initiates session with relay. } peers can now communicate through NATs via relay Application 2-91
Socket programming Goal: learn how to build client/server application that communicate using sockets Socket API socket } introduced in BSD4.1 UNIX, 1981 a host-local , } explicitly created, used, released application-created , by apps OS-controlled interface } client/server paradigm (a “door”) into which application process can } two types of transport service via both send and socket API: receive messages to/from } unreliable datagram another application } reliable, byte stream-oriented process Application 2-92
Socket-programming using TCP Socket: a door between application process and end-end- transport protocol (UCP or TCP) TCP service: reliable transfer of bytes from one process to another controlled by controlled by process application process developer application socket developer socket TCP with controlled by TCP with controlled by buffers, operating buffers, operating internet system system variables variables host or host or server server Application 2-93
Socket programming with TCP Client must contact server } when contacted by client, server TCP creates new socket for } server process must first be server process to communicate running with client } server must have created socket } allows server to talk with (door) that welcomes client’s contact multiple clients } source port numbers used to Client contacts server by: distinguish clients (more in } creating client-local TCP socket Chap 3) } specifying IP address, port application viewpoint number of server process } when client creates socket: TCP provides reliable, in-order client TCP establishes transfer of bytes (“pipe”) connection to server TCP between client and server Application 2-94
Client/server socket interaction: TCP Server (running on hostid ) Client create socket, port= x , for incoming request: welcomeSocket = ServerSocket() TCP create socket, wait for incoming connection setup connect to hostid , port= x connection request clientSocket = connectionSocket = Socket() welcomeSocket.accept() send request using clientSocket read request from connectionSocket write reply to connectionSocket read reply from clientSocket close connectionSocket close clientSocket Application 2-95
Streams keyboard monitor } stream is a sequence of characters that flow into or out of a process. inFromUser input stream } input stream is attached to some Client Process input source for the process, e.g., process keyboard or socket. } output stream is attached to an output source, e.g., monitor or socket. inFromServer outToServer output input stream stream client TCP clientSocket socket TCP socket to network from network Application 2-96
Socket programming with TCP Example client-server app: 1) client reads line from standard input ( inFromUser stream) , sends to server via socket ( outToServer stream) 2) server reads line from socket 3) server converts line to uppercase, sends back to client 4) client reads, prints modified line from socket ( inFromServer stream) Application 2-97
Example: Java client (TCP) import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; create BufferedReader inFromUser = input stream new BufferedReader(new InputStreamReader(System.in)); create client socket, Socket clientSocket = new Socket("hostname", 6789); connect to server create DataOutputStream outToServer = output stream new DataOutputStream(clientSocket.getOutputStream()); attached to socket Application 2-98
Example: Java client (TCP), cont. create BufferedReader inFromServer = input stream new BufferedReader(new attached to socket InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); send line outToServer.writeBytes(sentence + '\n'); to server modifiedSentence = inFromServer.readLine(); read line from server System.out.println ("FROM SERVER: " + modifiedSentence ); clientSocket.close(); } } Application 2-99
Example: Java server (TCP) import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; create welcoming socket ServerSocket welcomeSocket = new ServerSocket(6789); at port 6789 while(true) { wait, on welcoming socket for contact Socket connectionSocket = welcomeSocket.accept(); by client BufferedReader inFromClient = create input new BufferedReader(new stream, attached InputStreamReader(connectionSocket.getInputStream())); to socket Application 2-100
Recommend
More recommend