Chapter 3: Client Software Design Chapter 3: Client Software Design Chapter goal: Chapter goal: Algorithm and issues Algorithm and issues Concurrency in client Concurrency in client Client examples Client examples Learning algorithm instead of details Client architecture plication that uses TCP /IP mus Clients are conceptually simpler than servers functions and their exact parameters does not provide Most client does not explicitly handle designed, distributed concurrent interaction with multiple servers Most client executes as a conventional app If the pru how to do it is strang gram should do Most client does not need to enforce protect ams instead of memorizing the tails of a particular interface Identify a server Parsing an address argument Several methods to find a servers IP address and lient can use domain name or ip address to me or IP address as a constant in program: To determine whether the user has specified a name or an address. the client scans the Using a separate protocol to argument s Client sometimes need additional information e toc such as protocol port Building client that accepts a server address as an merinos. purdue edu smtp Single argument: server address merlin.cs, purdue. edussmtp Consistency is important
1 哈工大计算机学院 李全龙 Network Application Development Client Software Design 1 Chapter 3: Client Software Design Chapter goal: Algorithm and issues Concurrency in client Client examples 哈工大计算机学院 李全龙 Network Application Development Client Software Design 2 Chapter 3: Client Software Design Chapter goal: Algorithm and issues Concurrency in client Client examples 哈工大计算机学院 李全龙 Network Application Development Client Software Design 3 Learning algorithm instead of details An application that uses TCP/IP must specify many details about the desired communication. Knowing the low-level details of all possible socket functions and their exact parameters does not provide programmers with an understanding of how to build well-designed, distributed program. General understanding of the functions used for network communication is important. If the programmer knows what the program should do, finding out how to do it is straightforward. Although programmers need to understand the conceptual capabilities of the protocol interface, they should concentrate on learning about ways to structure communicating programs instead of memorizing the details of a particular interface. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 4 Client architecture Clients are conceptually simpler than servers. Most client does not explicitly handle concurrent interaction with multiple servers. Most client executes as a conventional app program. Most client does not need to enforce protections. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 5 Identify a server Several methods to find a server’s IP address and protocol port number: Domain name or IP address as a constant in program; Requiring user to identify; From stable storage; Using a separate protocol to find; Allowing the user to specify a server address when invoking client software makes the client program more general and makes it possible to change server locations. Building client that accepts a server address as an argument makes it easy to build extended versions of the software that use other ways to find the server address. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 6 Parsing an address argument Client can use domain name or IP address to identify the server machine. To determine whether the user has specified a name or an address, the client scans the argument. Client sometimes need additional information, such as protocol port. Two arguments: merlin.cs.purdue.edu smtp Single argument: merlin.cs.purdue.edu:smtp Consistency is important
Looking up a domain name hostent structure A client must specify the address of a server usin structure of stuct hostent oing so means converting an address in dotted mal notation(or domain name)i char FAr·FAB h_lengty: ontains a dotted decimal address and returns the char FAR·FAR· h addr list;P" list of address Function gethostbyname takes an ASCII string that #define h addr h addr_ listlol Fields that contain names and addresses must be lists because among other strings, the hosts IP address in binary The hostent structure is declared in include file Aadr refer to the first location in the host address list A program can use h addres if it were a field of structure Looking up a well-known port by Example for gethostbyname name stuct hostenthptr: Look up the protocol port for specific har' examplenam=“ merlin.cs. purdue. edu” service if(hptr=gethostbyname(example))t ame r IP address Two arguments A string that specifies the desired service Perror in name.handle it'l A string that specifies the protocol being used a Returns a pointer to a structure of type fo ccess lys cell stthtuste otr me returns a pointe servent Returns a NULL pointer. Defined in include file winsock. h servent structure Example stuct servent stuct servent sptr, char FAR s names name char FAR* FAR g aliases: /port for this service " if(sptr=getservbyname("smtp","tcp") char FAR /protocol to use port number is now in sptr>8_port"/ else i Perror occurred-handle it*/
2 哈工大计算机学院 李全龙 Network Application Development Client Software Design 7 Looking up a domain name A client must specify the address of a server using structure of sockaddr_in. Doing so means converting an address in dotted decimal notation (or domain name) into a 32-bit IP address. Function inet_addr takes an ASCII string that contains a dotted decimal address and returns the equivalent IP address in binary. Function gethostbyname takes an ASCII string that contains the domain name for a machine, and returns the address of a hostent structure that contains, among other strings, the host’s IP address in binary. The hostent structure is declared in include file winsock.h. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 8 hostent structure stuct hostent { char FAR* h_name; /*official host name */ char FAR* FAR* h_aliases; /*other aliases */ short h_addrtype; /*address type */ short h_lengty; /*address length */ char FAR* FAR* h_addr_list; /*list of address */ }; #define h_addr h_addr_list[0] Fields that contain names and addresses must be lists because of multiple interfaces. h_addr refer to the first location in the host address list. A program can use h_addr as if it were a field of structure hostent. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 9 Example for gethostbyname stuct hostent *hptr; char *examplenam=“merlin.cs.purdue.edu”; if (hptr=gethostbyname(example)){ /* IP address is now in hptr->h_addr*/ }else { /*error in name-handle it*/ } Successfully call, gethostbyname returns a pointer to a valid hostent struture. Otrerwise, Returns a NULL pointer. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 10 Looking up a well-known port by name Look up the protocol port for specific service. getservbyname Two arguments: A string that specifies the desired service A string that specifies the protocol being used Returns a pointer to a structure of type servent. Defined in include file winsock.h. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 11 servent structure stuct servent { char FAR* s_name; /*official service name */ char FAR* FAR* s_aliases; /*other aliases */ short s_port; /*port for this service */ char FAR* s_proto; /*protocol to use */ }; 哈工大计算机学院 李全龙 Network Application Development Client Software Design 12 Example stuct servent *sptr; if (sptr=getservbyname(“smtp”, “tcp”)){ /* port number is now in sptr->s_port*/ }else { /*error occurred-handle it*/ }
Port numbers and network byte order Looking up a protocol by name getservbyname returns the protocol port getprotobyname returns the address of a for the service in network byte orde structure of type protoent It is sufficient to understand that a Contained in winsock. h. getservbyname returns the port value in exactly the form needed for use in the sockaddr in structure char Far· char FAR'FAR. p aliases /list of aliases allowed " But, the representation may not agree with short official protocol number/ the local machine,'s usual representation. Example The TCP client algorithm stuct protoent*"pptr; ind the IP address and protocol port number if(pptrgetprotobyname("udp")) 2. Allocate a socket /official protocol number is now in pptr>p_proto Specify that the connection needs an arbitrary Perror occurred-handle it"/ Connect the socket to the server s, Communicate with the server using the application-layer protocols Close the connection Choosing a local protocol port Allocating a socket number #include <winsock h The client does not care which port it uses as long as SOCKETs: he port does not conf lict with the ports tl ther applications on the machine are already s=socket(PF_INET, SOCK_STREAM, 0: The port has not been assigned to a well-knowt The choice of a local port that meets the criteria listed above happens as a side effect of the connect call
3 哈工大计算机学院 李全龙 Network Application Development Client Software Design 13 Port numbers and network byte order getservbyname returns the protocol port for the service in network byte order. It is sufficient to understand that getservbyname returns the port value in exactly the form needed for use in the sockaddr_in structure. But, the representation may not agree with the local machine’s usual representation. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 14 Looking up a protocol by name getprotobyname returns the address of a structure of type protoent. Contained in winsock.h. stuct protoent { char FAR* p_name; /*official protocol name */ char FAR* FAR* p_aliases; /*list of aliases allowed*/ short p_proto; /*official protocol number*/ }; 哈工大计算机学院 李全龙 Network Application Development Client Software Design 15 Example stuct protoent *pptr; if (pptr=getprotobyname(“udp”)){ /* official protocol number is now in pptr->p_proto*/ }else { /*error occurred-handle it*/ } 哈工大计算机学院 李全龙 Network Application Development Client Software Design 16 The TCP client algorithm 1. Find the IP address and protocol port number of the server with which communication is desired. 2. Allocate a socket. 3. Specify that the connection needs an arbitrary, unused protocol port on the local machine, and allow TCP to choose one. 4. Connect the socket to the server. 5. Communicate with the server using the application-layer protocols. 6. Close the connection. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 17 Allocating a socket #include SOCKET s; s=socket(PF_INET, SOCK_STREAM, 0 ); 哈工大计算机学院 李全龙 Network Application Development Client Software Design 18 Choosing a local protocol port number The client does not care which port it uses as long as : The port does not conflict with the ports that other applications on the machine are already using. The port has not been assigned to a well-known service. The choice of a local port that meets the criteria listed above happens as a sideeffect of the connect call
Choosing a local IP address Choosing a local IP address a client must choose ress as well as a To solve the problem, the socket functions make it possible for an application to leave the local IP address field unfilled and to allow TCP/IP software a The difficulty in choosing an IP address to choose a local IP address automatically at the time the client connects to a serve ations seldom have access to routi Because choosing the correct local IP address software TcP client software usually leaves t equires the application to interact with IP routing network interface over which IP routes the local endpoint address unfilled, and allows TCP/IP software to select the correct local IP address and lipicult and confusing? ing an incorrect address violates the ification an unused local protocol port number automatically. and makes the program Connecting a TCP socket to a Connecting a TCP socket to a server server a connect function connect forces the initial TCP 3-way handshaking Socket is the descriptor for a socket The call to connect does not return until a TCP connection has been established or TCp Remaddr is the address of a structure of reaches timeout threshold and gives up type sockaddr_ in that specifies the remote to which a connection is desired The call returns O if the connection attempt succeeds or socKET ERROR if it fails a Remaddrlen is the length of remaddr Connecting a TCP socket to a Communicating with the server p server using TCP connect performs four Test to ensure that the ed socket is valid Usually request-response interaction. and that it has not already been connected A client call send to transmit each request Fills in the remote endpoint address in the socket and recv to await a response. from the second argumen a For example Chooses a local endpoint address for the connection(IP address and protocol port number) if the socket does not have one Initiates a TcP connection and returns a value to tell the caller whether the connection succeeded
4 哈工大计算机学院 李全龙 Network Application Development Client Software Design 19 Choosing a local IP address A client must choose a local IP address as well as a local port number. Gateways (routers) or multihomed hosts have multiple IP addresses. The difficulty in choosing an IP address arises because the correct choice depends on routing and applications seldom have access to routing information. Problem: the IP source address in an outgoing datagram should match the IP address of the network interface over which IP routes the datagram. Using an incorrect address violates the specification, makes network management difficult and confusing, and makes the program less reliable. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 20 Choosing a local IP address To solve the problem, the socket functions make it possible for an application to leave the local IP address field unfilled and to allow TCP/IP software to choose a local IP address automatically at the time the client connects to a server. Because choosing the correct local IP address requires the application to interact with IP routing software, TCP client software usually leaves the local endpoint address unfilled, and allows TCP/IP software to select the correct local IP address and an unused local protocol port number automatically. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 21 Connecting a TCP socket to a server connect function connect forces the initial TCP 3-way handshaking. The call to connect does not return until a TCP connection has been established or TCP reaches timeout threshold and gives up. The call returns 0 if the connection attempt succeeds or SOCKET_ERROR if it fails. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 22 Connecting a TCP socket to a server Socket is the descriptor for a socket; Remaddr is the address of a structure of type sockaddr_in that specifies the remote endpoint to which a connection is desired; Remaddrlen is the length of remaddr. connect(socket,remaddr,remaddrlen); 哈工大计算机学院 李全龙 Network Application Development Client Software Design 23 Connecting a TCP socket to a server connect performs four tasks: Test to ensure that the specified socket is valid and that it has not already been connected; Fills in the remote endpoint address in the socket from the second argument; Chooses a local endpoint address for the connection (IP address and protocol port number) if the socket does not have one; Initiates a TCP connection, and returns a value to tell the caller whether the connection succeeded. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 24 Communicating with the server using TCP Usually request-response interaction. A client call send to transmit each request and recv to await a response. For example:
Communicating with the server Reading response from a TCl using TCP connection a TCP is not a block-oriented protocol, is a eqf"request of some /buffer for answer stream-oriented protocol es read *y TCP guarantees to deliver the sequence of bytes intbuflen space left in buffer that the sender writes, but it does not guarantee to deliver them in the same grouping as they were a Because tp does no boundaries, any progr reads from a TCP connection mus while(nl= SOCKET ERROR & nl=o) ared to accept data a few bytes at a nErev(s, bptr buflen, O) This rule holds even if the sending applicatio writes data in large blocks Closing a TCP connection A partial close operation closesocket terminates the connection .n shutdown function takes two parameters gracefully and deallocate the socket. Closing a connection is not simple because of Direction errcode= shutdown( s, direction Closing a connection usually requires coordination among the client and server further input is allowed To solve the connection shutdown problem 1-no further output is allowed most implementations of the socket interface include an additional primitive that permits pplication to shut down a TCP connection in Advantage: end-of-file si one direction arbitrary amounts of nformation in resporse to a request, Programming a UDP client Connected and unconnected UDP algorithm socke ts Find the IP address and protocol port number basic UDP socket mode: of the server with which communication is Specify machine Communicate with the server using the nt 4.Specify the server which messages to UDP sockets can be connected, making it conventional to interact with a specific server, or they can be connected, making it necessary for the application 6. Close the connection to specify the servers address each time it sends a
5 哈工大计算机学院 李全龙 Network Application Development Client Software Design 25 Communicating with the server using TCP #define BLEN 120 /*buffer length to use */ char *req=“request of some sort”; char buf[BLEN]; /*buffer for answer */ char *bptr; /*pointer to buffer */ int n; /*number of bytes read */ int buflen; /*space left in buffer */ Bptr=buf; buflen=BLEN; /*send request*/ send(s,req,strlen(req),0); /*read response (may come in many pieces)*/ n=recv(s,bptr,buflen,0); while(n!=SOCKET_ERROR && n!=0){ bptr+=n; buflen-=n; n=recv(s,bptr,buflen,0); } 哈工大计算机学院 李全龙 Network Application Development Client Software Design 26 Reading response from a TCP connection TCP is not a block-oriented protocol, is a stream-oriented protocol. TCP guarantees to deliver the sequence of bytes that the sender writes, but it does not guarantee to deliver them in the same grouping as they were wirten. Because TCP does not preserve record boundaries, any program that reads from a TCP connection must be prepared to accept data a few bytes at a time. This rule holds even if the sending application writes data in large blocks. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 27 Closing a TCP connection closesocket terminates the connection gracefully and deallocate the socket. Closing a connection is not simple because of full-duplex. Closing a connection usually requires coordination among the client and server. To solve the connection shutdown problem, most implementations of the socket interface include an additional primitive that permits application to shut down a TCP connection in one direction. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 28 A partial close operation shutdown function takes two parameters: A socket descriptor Direction errcode = shutdown( s, direction); Integer: 0-no further input is allowed; 1-no further output is allowed; 2-both direction. Advantage: end-of-file signal. The partial close mechanism removes ambiguity for application protocols that transmit arbitrary amounts of information in response to a request. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 29 Programming a UDP clientalgorithm 1. Find the IP address and protocol port number of the server with which communication is desired. 2. Allocate a socket. 3. Specify that the communication needs an arbitrary, unused protocol port on the local machine, and allow UDP to choose one. 4. Specify the server which messages to sent. 5. Communicate with the server using the application-layer protocol. 6. Close the connection. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 30 Connected and unconnected UDP sockets Two basic UDP socket mode: Connected Unconnected Advantages: Connected: the application need specify the server only once. Unconnected: flexibility, communicate with different servers. UDP sockets can be connected, making it conventional to interact with a specific server, or they can be unconnected, making it necessary for the application to specify the server’s address each time it sends a message
Communicating with a server Using connect with UDP using UDP The connect call does not initiate any packet exchange, nor does it test the validity of the UDP provides message transfer remote endpoint address Connect mode It merely records the remote endpoint Using send and recv to send or receive a information in the socket data structure for later use UDP client does not need to make Even if connect call succeeds, it does not repeated calls to recv to obtain a sing mean that the remote endpoint address is valid or that the server if reachable UdP does not need repeated call to recy Closing a socket that uses UDP About UDP unreliability Calls closesocket like tcP but does not Client software that uses UDP must inform the remote endpoint implement reliability with techniques lil Partial close for UDP packet sequencing, acknowledgements shutdown can be used with a connected UDP timeout and efficient for an internet socket to stop further transmission in a given environment requires consideration direction. expertise Unlike TCP, shutdown does not send any How to build reliable apps over UDP? messages to the other side It to transfer data in the direction(s)specified Chapter 3: Client Software Design Advantages of concurrency Chapter goal: Algorithm and issues Potential deadlocks a Concurrency in client Client examples s Client Easier to program: Separate functionality into conceptually tatus, or control processing dynamical The key advantage lies in( 6
6 哈工大计算机学院 李全龙 Network Application Development Client Software Design 31 Using connect with UDP The connect call does not initiate any packet exchange, nor does it test the validity of the remote endpoint address. It merely records the remote endpoint information in the socket data structure for later use. Even if connect call succeeds, it does not mean that the remote endpoint address is valid or that the server if reachable. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 32 Communicating with a server using UDP UDP provides message transfer. Connect mode Using send and recv to send or receive a message. UDP client does not need to make repeated calls to recv to obtain a single message. UDP does not need repeated call to recv 哈工大计算机学院 李全龙 Network Application Development Client Software Design 33 Closing a socket that uses UDP Calls closesocket like TCP, but does not inform the remote endpoint. Partial close for UDP shutdown can be used with a connected UDP socket to stop further transmission in a given direction. Unlike TCP, shutdown does not send any messages to the other side. It merely marks the local socket as unwilling to transfer data in the direction(s) specified. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 34 About UDP unreliability Client software that uses UDP must implement reliability with techniques like packet sequencing, acknowledgements, timeout, and efficient for an internet environment requires consideration expertise. How to build reliable apps over UDP? Home work…… 哈工大计算机学院 李全龙 Network Application Development Client Software Design 35 Chapter 3: Client Software Design Chapter goal: Algorithm and issues Concurrency in client Client examples 哈工大计算机学院 李全龙 Network Application Development Client Software Design 36 Advantages of concurrency Server Response time Potential deadlocks Multiprotocol & multiservice servers portability Client Easier to program: Separate functionality into conceptually separate components Easier to maintain and extend: modular Can contact several servers at the same time Allow users to change parameters, inquire about the client status, or control processing dynamically The key advantage lies in asynchrony
Concurrent contact with multiple Motivation for exercising control servers Separate control functions from normal processing Concurrency can allow a single client to Uncertain response time and response size contact several servers at the same time and Most client merely waits until a response arrives report to the user as soon as it receives from Concurrency can help any of them F the client while the client waits for a respons User can find out whether any data has been received. choose to send a different request, or terminate eparating client control from normal processing allows a user to interact with a client even if the normal input for the client comes from a fil Implementing concurrent clients Implementing concurrent clients Two basic approaches The client divides into two or more threads The client divides into two or more threads that each handle that each handle one function one funct The client consists of a single thread that use Implementing concurrent clients Chapter 3: Client Software Design Two basic approaches Chapter goal: Algorithm and issues in client Client thread
7 哈工大计算机学院 李全龙 Network Application Development Client Software Design 37 Motivation for exercising control Separate control functions from normal processing Uncertain response time and response size Most client merely waits until a response arrives Deadlock may occur Concurrency can help Concurrent client can permit user to continue interact with the client while the client waits for a response User can find out whether any data has been received, choose to send a different request, or terminate Separating client control from normal processing allows a user to interact with a client even if the normal input for the client comes from a file. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 38 Concurrent contact with multiple servers Concurrency can allow a single client to contact several servers at the same time and report to the user as soon as it receives from any of them For example 哈工大计算机学院 李全龙 Network Application Development Client Software Design 39 Implementing concurrent clients Two basic approaches The client divides into two or more threads that each handle one function The client consists of a single thread that uses select to handle multiple input and output events asynchronously 哈工大计算机学院 李全龙 Network Application Development Client Software Design 40 Implementing concurrent clients Two basic approaches The client divides into two or more threads that each handle one function The client consists of a single thread that uses select to handle multiple input and output events asynchronously control input output Control descriptor input TCP socket output Client threads Operating system 哈工大计算机学院 李全龙 Network Application Development Client Software Design 41 Implementing concurrent clients Two basic approaches The client divides into two or more threads that each handle one function The client consists of a single thread that uses select to handle multiple input and output events asynchronously client input TCP socket1 TCP socket2 TCP socketn Client thread Operating system … 哈工大计算机学院 李全龙 Network Application Development Client Software Design 42 Chapter 3: Client Software Design Chapter goal: Algorithm and issues Concurrency in client Client examples
Example client software Implementation of Con TCP The first step of Place all the de ewinsockhy Easy to understand low level SOCKET cornectsockconst char*const char code into orst char Intuitive understanding connectTaP-connect to a specified TOP service iding details on a specified he share connectTaP(const char *host, const char *service Reduce the chance for error Isolate the Os dependency A procedure that forms Implementation of ConUDP connections a Used to conUDP, cPp-connectUDP*/ / connock, cpp-conrectsock"/ OCKET connectsock(const char*, corst char connected const char *E socket that #include <. hp cornectUDP-connect to a specified UDP service on a specified host DR NONE Oxffffffff OCKET # endif INADDR NONE” cornectUDP(const char *host, const char service return connectsock(host, service, udp): connectsock-allocate connect a socket using TOP or UDP A procedure that forms A procedure that forms connections(cont) connections(cont) onrectsock(const char *host, const char *service, const char *transport Ar',, service) to protocol information entry * struct sockaddr _in sin: /an Internet endpoint address Map host name to IP address, allowing for dotted decimal * int s, type, socket descriptor and socket typ f(phe s gethostbyname(host)) memset(&sin, O, sizeof(sin)): errexitccan't get \"Ys\"host entry \n", host)- sin,sin-family AF_INE f((pe s getprotobyname(transport))=o) 8
8 哈工大计算机学院 李全龙 Network Application Development Client Software Design 43 Example client software Importance of small examples Easy to understand Highlight fundamental algorithm Intuitive understanding Hiding details Modular program Easy to port Procedures raise the level of the language-reuse Use of procedures is important when building C/S programs Reduce the chance for error Reuse the code Isolate the OS dependency The first step of designing a procedure lib is abstraction The procedure abstraction allows programmers to define high-level operations, share code among applications. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 44 Implementation of ConTCP Place all the low level code into connectsock procedure /* conTCP.cpp - connectTCP */ #include SOCKET connectsock(const char *, const char *, const char *); /*---------------------------------------------------- * connectTCP - connect to a specified TCP service * on a specified host *-------------------------------------------------- */ SOCKET connectTCP(const char *host, const char *service ) { return connectsock( host, service, "tcp"); } 哈工大计算机学院 李全龙 Network Application Development Client Software Design 45 Implementation of ConUDP Used to establish a connected socket that uses UDP /* conUDP.cpp - connectUDP */ #include SOCKET connectsock(const char *, const char *, const char *); /*------------------------------------------------------- * connectUDP - connect to a specified UDP service * on a specified host *-----------------------------------------------------*/ SOCKET connectUDP(const char *host, const char *service ) { return connectsock(host, service, "udp"); } 哈工大计算机学院 李全龙 Network Application Development Client Software Design 46 A procedure that forms connections /* consock.cpp - connectsock */ #include #include #include #include #ifndef INADDR_NONE #define INADDR_NONE 0xffffffff #endif /* INADDR_NONE */ void errexit(const char *, ...); /*------------------------------------------------------------------------ * connectsock - allocate & connect a socket using TCP or UDP *------------------------------------------------------------------------ */ 哈工大计算机学院 李全龙 Network Application Development Client Software Design 47 A procedure that forms connections (cont.) SOCKET connectsock(const char *host, const char *service, const char *transport ) { struct hostent *phe; /* pointer to host information entry */ struct servent *pse; /* pointer to service information entry */ struct protoent *ppe; /* pointer to protocol information entry */ struct sockaddr_in sin;/* an Internet endpoint address */ int s, type; /* socket descriptor and socket type */ memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; 哈工大计算机学院 李全龙 Network Application Development Client Software Design 48 A procedure that forms connections (cont.) /* Map service name to port number */ if ( pse = getservbyname(service, transport) ) sin.sin_port = pse->s_port; else if ( (sin.sin_port = htons((u_short)atoi(service))) == 0 ) errexit("can't get \"%s\" service entry\n", service); /* Map host name to IP address, allowing for dotted decimal */ if ( phe = gethostbyname(host) ) memcpy(&sin.sin_addr, phe->h_addr, phe->h_length); else if ( (sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE) errexit("can't get \"%s\" host entry\n", host); /* Map protocol name to protocol number */ if ( (ppe = getprotobyname(transport)) == 0) errexit("can't get \"%s\" protocol entry\n", transport);
A procedure that forms A procedure that forms connections(cont) connections(cont) A errexit, cpp-errexit * #include <stdlib. hp type= SOCK_STREAM; if (s== INVALID SOCKET) socket: d\n, GetLast Error O) d errexit(const char *format, n) if (connect(s, (struct sockaddr "sin, sizeof(sin))=z printf(stderr, format, args) rexit(cant connect to Zs,Ys: %d\n", host, service, GetLastErrorO: WSAClearupO: Implementation of a TCP client Client examples-1 for DAyTIME The DAy TIME service / TCPdte. cpp-main, TCPdaytime"/ Available for both TCP and UDP, port 13 The TCP version uses the presence of a TaI void TaPdaytime(const char const char *) connection to trigger output The UDP version needs the client to send a SOCKET connect TCP(const char*, const char *E request #define LINELEN #define WSVERS MAKEWORD(2. c main-ToP client for DAY TIME se Implementation of a TCP client &-I Implementation of a TcP client for DAyTIME(cont for DAyT工ME(cont) default: rinf(stderr, usage: TCPdaytime [host [port]]\n") char *host :"localhost" st to use if f (WSAStartup(WSVERS, &wsadata)I= O) rexit("wSAStartup failed\n") Daytime(host, service): host s"localhost" SACleanupo service= argv[2]: TCPdaytime-inmvoke Daytime on specified host and print results host a argv[l]
9 哈工大计算机学院 李全龙 Network Application Development Client Software Design 49 A procedure that forms connections (cont.) /* Use protocol to choose a socket type */ if (strcmp(transport, "udp") == 0) type = SOCK_DGRAM; else type = SOCK_STREAM; /* Allocate a socket */ s = socket(PF_INET, type, ppe->p_proto); if (s == INVALID_SOCKET) errexit("can't create socket: %d\n", GetLastError()); /* Connect the socket */ if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) == SOCKET_ERROR) errexit("can't connect to %s.%s: %d\n", host, service, GetLastError()); return s;} 哈工大计算机学院 李全龙 Network Application Development Client Software Design 50 A procedure that forms connections (cont.) /* errexit.cpp - errexit */ #include #include #include #include /*------------------------------------------------------------------------ * errexit - print an error message and exit *------------------------------------------------------------------------ */ /*VARARGS1*/ void errexit(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); WSACleanup(); exit(1);} 哈工大计算机学院 李全龙 Network Application Development Client Software Design 51 Client examples-1 The DAYTIME service Obtain the day and time Available for both TCP and UDP, port 13 The TCP version uses the presence of a TCP connection to trigger output The UDP version needs the client to send a request 哈工大计算机学院 李全龙 Network Application Development Client Software Design 52 Implementation of a TCP client for DAYTIME /* TCPdtc.cpp - main, TCPdaytime */ #include #include #include void TCPdaytime(const char *, const char *); void errexit(const char *, ...); SOCKET connectTCP(const char *, const char *); #define LINELEN 128 #define WSVERS MAKEWORD(2, 0) /*------------------------------------------------------------------------ * main - TCP client for DAYTIME service *------------------------------------------------------------------------ */ 哈工大计算机学院 李全龙 Network Application Development Client Software Design 53 Implementation of a TCP client for DAYTIME (cont.) Int main(int argc, char *argv[]) { char *host = "localhost"; /* host to use if none supplied */ char *service = "daytime"; /* default service port */ WSADATA wsadata; switch (argc) { case 1: host = "localhost"; break; case 3: service = argv[2]; /* FALL THROUGH */ case 2: host = argv[1]; break; 哈工大计算机学院 李全龙 Network Application Development Client Software Design 54 Implementation of a TCP client for DAYTIME (cont.) default: fprintf(stderr, "usage: TCPdaytime [host [port]]\n"); exit(1); } if (WSAStartup(WSVERS, &wsadata) != 0) errexit("WSAStartup failed\n"); TCPdaytime(host, service); WSACleanup(); return 0; /* exit */ } /*------------------------------------------------------------------------ * TCPdaytime - invoke Daytime on specified host and print results *------------------------------------------------------------------------ */
Implementation of a TcP client . for DAyTIME(cont) Client examples-2 woid TCPdaytime(corst char *host, const char *service) The TIME service and time from anoth char buf [LINELEN-1]: Time and day information must be represented in s= connect TCP(host, service) TIME service is intended for use by programs that store ce= recv(s, buf. LINELEN, O): es time in a 32-bit integer, representing while( ce SOCKET_ ERROR TIME Uses midnight,, J A ensure null-termingtion Available for both tCP and UDP uts(buf, stdout): The TCP version uses the presence of a TCP connectio ce- recv(s, buf. LINELEN, O) nt to send a request TIME does not handle the problem of network latency A UDP Client for the TIME A UDP Client for the TIME service service(cont) DPtime cpp-main void errexit(const char*E main-UDP client for TIME service that prints the resulting #include ctime. hp #include <winsock. h int main(int arge, char *argD #define BUFSIZE lAKEWORD(2, o) ar *host ="localhost"; / host to use if none supplie ar’ service="time #define WINEPOCH 2208988800/Windows epoch, in UCT secs*/ 32-bit integer to hold time " hat time is it?\n" socket descriptor recv count SOCKET WSADATA wsadata A UDP Client for the TIME A UDP Client for the TIME service(cont) service(cont) switch(argc rexit( WsAStartup failed\n") host="localhost" (void) send(s, MSG. strler(MSG). 0): FALL THROUGH * if (n== SOCKET ERROR) host a argv[l] rexit(recv failed: recv error %d\n, GetLastError o) fprintf(stderr, "usage: UDPtime [host [portI]\n") /convert UCT to windows epoch*/ printf"Ys", ctime(&now): return 0: exit *
10 哈工大计算机学院 李全龙 Network Application Development Client Software Design 55 Implementation of a TCP client for DAYTIME (cont.) void TCPdaytime(const char *host, const char *service) { char buf[LINELEN+1]; /* buffer for one line of text */ SOCKET s; /* socket descriptor */ int cc; /* recv character count */ s = connectTCP(host, service); cc = recv(s, buf, LINELEN, 0); while( cc != SOCKET_ERROR && cc > 0) { buf[cc] = '\0'; /* ensure null-termination */ (void) fputs(buf, stdout); cc = recv(s, buf, LINELEN, 0); } closesocket(s); } Because the TCP stream service does not guarantee to deliver data in the same blocks that it was writen, an application receiving data from a TCP connection cannot depend on all data being delivered in a single transfer; it must repeatedly call recv until all data has been obtained. 哈工大计算机学院 李全龙 Network Application Development Client Software Design 56 Client examples-2 The TIME service Obtain the day and time from another machine similar to DAYTIME service Time and day information must be represented in Universal Coordinated Time TIME service is intended for use by programs that store or manipulate times Always specifies time in a 32-bit integer, representing the number of seconds since an epoch date TIME Uses midnight, January 1, 1900, as its epoch Available for both TCP and UDP, port 37 The TCP version uses the presence of a TCP connection to trigger output The UDP version needs the client to send a request TIME does not handle the problem of network latency 哈工大计算机学院 李全龙 Network Application Development Client Software Design 57 A UDP Client for the TIME service /* UDPtime.cpp - main */ #include #include #include #include #define BUFSIZE 64 #define WSVERS MAKEWORD(2, 0) #define WINEPOCH 2208988800 /* Windows epoch, in UCT secs */ #define MSG "what time is it?\n" SOCKET connectUDP(const char *, const char *); 哈工大计算机学院 李全龙 Network Application Development Client Software Design 58 A UDP Client for the TIME service (cont.) void errexit(const char *, ...); /*------------------------------------------------------------------------ * main - UDP client for TIME service that prints the resulting time *------------------------------------------------------------------------ */ int main(int argc, char *argv[]) { char *host = "localhost"; /* host to use if none supplied */ char *service = "time"; /* default service name */ time_t now; /* 32-bit integer to hold time */ SOCKET s; /* socket descriptor */ int n; /* recv count */ WSADATA wsadata; 哈工大计算机学院 李全龙 Network Application Development Client Software Design 59 A UDP Client for the TIME service (cont.) switch (argc) { case 1: host = "localhost"; break; case 3: service = argv[2]; /* FALL THROUGH */ case 2: host = argv[1]; break; default: fprintf(stderr, "usage: UDPtime [host [port]]\n"); exit(1); } 哈工大计算机学院 李全龙 Network Application Development Client Software Design 60 A UDP Client for the TIME service (cont.) if (WSAStartup(WSVERS, &wsadata)) errexit("WSAStartup failed\n"); s = connectUDP(host, service); (void) send(s, MSG, strlen(MSG), 0); /* Read the time */ n = recv(s, (char *)&now, sizeof(now), 0); if (n == SOCKET_ERROR) errexit("recv failed: recv() error %d\n", GetLastError()); WSACleanup(); now = ntohl((u_long)now); /* put in host byte order */ now -= WINEPOCH; /* convert UCT to Windows epoch*/ printf("%s", ctime(&now)); return 0; /* exit */ }