Sie sind auf Seite 1von 15

The client server model Most interprocess communication uses the client server model.

These terms refer to the two processes which will be communicating with each other. One of the two processes, the client, connects to the other process, the server, typically to make a request for information. A good analogy is a person who makes a phone call to another person. Notice that the client needs to know of the existence of and the address of the ser er, but the ser er does not need to know the address of the client prior to the connection being established. Notice also that once a connection is established, both sides can send and recei e information. The system calls for establishing a connection are somewhat different for the client and the ser er, but both in ol e the basic construct of a socket.A socket is one end of an interprocess communication channel. The two processes each establish their own socket. A socket is a bidirectional communication de ice that can be used to communicate with another process on the same machine or with a process running on other machines. The steps in ol ed in establishing a socket on the client side are as follows! ". #reate a socket with the socket$% system call &. #onnect the socket to the address of the ser er using the connect$% system call '. (end and recei e data. There are a number of ways to do this, but the simplest is to use the read $% and write $% system calls.

The steps in ol ed in establishing a socket on the server side are as follows! ". #reate a socket with the socket$% system call &. )ind the socket to an address using the bind $% system call. *or a ser er socket on the +nternet, an address consists of a port number on the host machine. '. ,isten for connections with the listen$% system call -. Accept a connection with the accept$% system call. This call typically blocks until a client connects with the ser er. .. (end and recei e data System Calls (ockets are more flexible than other communication techniques. These are the system calls in ol ing sockets! socket/#reates a socket closes/0estroys a socket connect/#reates a connection between two sockets bind/,abels a ser er socket with an address listen/#onfigures a socket to accept conditions accept/Accepts a connection and creates a new socket for the connection (ockets are represented by file descriptors. Socket Concepts 1hen you create a socket, you must specify three parameters! communication style, namespace, and protocol. A communication style controls how the socket treats transmitted data and specifies the number of communication partners. 1hen data is sent through a socket, it is packaged into chunks called packets. The communication style determines how these packets are handled and how they are addressed from the sender to the recei er. #onnection styles guarantee deli ery of all packets in the order they were sent. +f packets are lost or reordered by
2

problems in the network, the recei er automatically requests their retransmission from the sender. A connection2style socket is like a telephone call! The addresses of the sender and recei er are fixed at the beginning of the communication when the connection is established. 0atagram styles do not guarantee deli ery or arri al order. 3ackets may be lost or reordered in transit due to network errors or other conditions. 4ach packet must be labeled with its destination and is not guaranteed to be deli ered. The system guarantees only 5best effort,6 so packets may disappear or arri e in a different order than shipping. A datagram2style socket beha es more like postal mail. The sender specifies the recei er7s address for each indi idual message. A socket namespace specifies how socket addresses are written. A socket address identifies one end of a socket connection. *or example, socket addresses in the 5local namespace6 are ordinary filenames. +n 5+nternet namespace,6 a socket address is composed of the +nternet address $also known as an +nternet 3rotocol address or +3 address% of a host attached to the network and a port number. The port number distinguishes among multiple sockets on the same host. A protocol specifies how data is transmitted. (ome protocols are T#38+3, the primary networking protocols used by the +nternet9 the AppleTalk network protocol9 and the :N+; local communication protocol. Creating and Destroying Sockets The socket and close functions create and destroy sockets, respecti ely. 1hen you create a socket, specify the three socket choices! namespace, communication style, and protocol.
3

*or the namespace parameter, use constants beginning with A*< $abbre iating 5Address families6%. *or example, A*<,O#A, or A*<:N+; specifies the local namespace, and A*<+N4T specifies +nternet namespaces. *or the communication style parameter, use constants beginning with (O#=<. :se (O#=<(T>4AM for a connection2style socket, or use (O#=<0?>AM for a datagram2style socket. The third parameter, the protocol, specifies the low2le el mechanism to transmit and recei e data. )ecause there is usually one best protocol for each such pair, specifying @ is usually the correct protocol. +f socket succeeds, it returns a file descriptor for the socket.Aou can read from or write to the socket using read, write, and so on, as with other file descriptors.1hen you are finished with a socket, call close to remo e it. BincludeCstdio.hD BincludeCsys8socket.hD int main$int argc , char Earg FG% H int socket<desc9 socket<desc I socket$A*<+N4T , (O#=<(T>4AM , @%9 if $socket<desc II 2"% H printf$J#ould not create socketJ%9 K return @9 K
4

*unction socket$% creates a socket and returns a socket descriptor which can be used in other network commands. Calling connect To create a connection between two sockets, the client calls connect, specifying the address of a ser er socket to connect to. A client is the process initiating the connection, and a ser er is the process waiting to accept connections. The client calls connect to initiate a connection from a local socket to the ser er socket specified by the second argument. The third argument is the length, in bytes, of the address structure pointed to by the second argument. (ocket address formats differ according to the socket namespace. Sample code ser er.c client.c compile them separately into two executables called ser er and client. +deally, you should run the client and the ser er on separate hosts on the +nternet. (tart the ser er first. (uppose the ser er is running on a machine called cheerios. 1hen you run the ser er, you need to pass the port number in as an argument. Aou can choose any number between &@@@ and L..'.. +f this port is already in use on that machine, the ser er will tell you this and exit. +f this happens, Must choose another port and try again. +f the port is a ailable, the ser er will block until it recei es a connection from the client. 0onNt be alarmed if the ser er doesnNt do anything9+tNs not supposed to do anything until a connection is made. Oere is a typical command line!
5

server 51717 To run the client you need to pass in two arguments, the name of the host on which the ser er is running and the port number on which the ser er is listening for connections. Oere is the command line to connect to the ser er described abo e! client cheerios 51717 The client will prompt you to enter a message. +f e erything works correctly, the ser er will display your message on stdout, send an acknowledgement message to the client and terminate. The client will print the acknowledgement message from the ser er and then terminate. Aou can simulate this on a single machine by running the ser er in one window and the client in another. +n this case, you can use the keyword localhost as the first argument to the client. Server Code The ser er code uses a number of ugly programming constructs, and so we will go through it line by line. #include <sys/types.h> This header file contains definitions of a number of data types used in system calls. These types are used in the next two include files. #include <sys/socket.h> The header file socket.h includes a number of definitions of structures needed for sockets. #include <netinet/in.h>
6

The header file in.h contains constants and structures needed for internet domain addresses. oid error$char Emsg% { " perror(msg) e!it(1)

This function is called when a system call fails. +t displays a message about the error on stderr and then aborts the program. int main(int argc# char $argv%&) { int sock'd# ne(sock'd# portno# clilen# n sock'd and ne(sock'd are file descriptors. These two ariables store the alues returned by the socket system call and the accept system call. portno stores the port number on which the ser er accepts connections. clilen stores the siPe of the address of the client. This is needed for the accept system call. n is the return alue for the read() and (rite() calls9 i.e. it contains the number of characters read or written. char )u''er%*5+& The ser er reads characters from the socket connection into this buffer. struct sockaddr,in serv,addr# cli,addr A sockaddr,in is a structure containing an internet address. This structure is defined in netinet/in.h.
7

Oere is the definition! struct sockaddr,in { short sin,'amily /$ must )e -.,/012 $/ u,short sin,port struct in,addr sin,addr char sin,3ero%4& /$ 0ot used# must )e 3ero $/ " The ariable serv,addr will contain the address of the ser er, and cli,addr will contain the address of the client which connects to the ser er. i' (argc < *) { 'print'(stderr#516676# no port provided5) e!it(1) " The user needs to pass in the port number on which the ser er will accept connections as an argument. This code displays an error message if the user fails to do this. sock'd 8 socket(-.,/012# 97:;,9261-<# =) i' (sock'd < =) error(516676 opening socket5) The socket() system call creates a new socket. +t takes three arguments. The first is the address domain of the socket. +f the socket call fails, it returns 2". +n this case the program displays and error message and exits. )3ero((char $) >serv,addr# si3eo'(serv,addr)) The function )3ero() sets all alues in a buffer to Pero. +t takes two arguments, the first is a pointer to the buffer and the second
8

is the siPe of the buffer. Thus, this line initialiPes serv,addr to Peros. 2222 portno 8 atoi(argv%1&) The port number on which the ser er will listen for connections is passed in as an argument, and this statement uses the atoi() function to con ert this from a string of digits to an integer. serv,addr.sin,'amily 8 -.,/012 The ariable serv,addr is a structure of type struct sockaddr,in. This structure has four fields. The first field is short sin,'amily, which contains a code for the address family. +t should always be set to the symbolic constant -.,/012. serv,addr.sin,port 8 htons(portno) The second field of serv,addr is unsigned short sin,port, which contain the port number. Oowe er, instead of simply copying the port number to this field, it is necessary to con ert this to network byte order using the function htons() which con erts a port number in host byte order to a port number in network byte order. serv,addr.sin,addr.s,addr 8 /0-??6,-0@ The third field of sockaddr,in is a structure of type struct in,addr which contains only a single field unsigned long s,addr. This field contains the +3 address of the host. *or ser er code, this will always be the +3 address of the machine on which the ser er is running, and there is a symbolic constant /0-??6,-0@ which gets this address. i' ()ind(sock'd# (struct sockaddr $) >serv,addr#si3eo'(serv,addr)) < =) error(516676 on )inding5)
9

The )ind() system call binds a socket to an address, in this case the address of the current host and port number on which the ser er will run. +t takes three arguments, the socket file descriptor, the address to which is bound, and the siPe of the address to which it is bound. listen(sock'd#5) The listen system call allows the process to listen on the socket for connections. The first argument is the socket file descriptor, and the second is the siPe of the backlog queue, i.e., the number of connections that can be waiting while the process is handling a particular connection. This should be set to ., the maximum siPe permitted by most systems. clilen 8 si3eo'(cli,addr) ne(sock'd 8 accept(sock'd# (struct sockaddr $) >cli,addr# >clilen) i' (ne(sock'd < =) error(516676 on accept5) The accept() system call causes the process to block until a client connects to the ser er. Thus, it wakes up the process when a connection from a client has been successfully established. +t returns a new file descriptor, and all communication on this connection should be done using the new file descriptor. The second argument is a reference pointer to the address of the client on the other end of the connection, and the third argument is the siPe of this structure. )3ero()u''er#*5+) n 8 read(ne(sock'd#)u''er#*55) i' (n < =) error(516676 reading 'rom socket5) print'(5Aere is the messageB Cs#)u''er)
10

Note that we would only get to this point after a client has successfully connected to our ser er. This code initialiPes the buffer using the )3ero() function, and then reads from the socket. Note that the read call uses the new file descriptor, the one returned by accept(), not the original file descriptor returned by socket(). Note also that the read() will block until there is something for it to read in the socket, i.e. after the client has executed a (rite(). +t will read either the total number of characters in the socket or &.., whiche er is less, and return the number of characters read. n 8 (rite(ne(sock'd#5/ got your message5#14) i' (n < =) error(516676 (riting to socket5) Once a connection has been established, both ends can both read and write to the connection. Naturally, e erything written by the client will be read by the ser er, and e erything written by the ser er will be read by the client. This code simply writes a short message to the client. The last argument of write is the siPe of the message. return = " This terminates main and thus the program. (ince main was declared to be of type int as specified by the ascii standard, some compilers complain if it does not return anything. Client code #include #include #include #include #include <stdio.h> <sys/types.h> <sys/socket.h> <netinet/in.h> <netd).h>
11

The header files are the same as for the ser er with one addition. The file netd).h defines the structure hostent, which will be used below. void error(char $msg) { perror(msg) e!it(=) " int main(int argc# char $argv%&) { int sock'd# portno# n struct sockaddr,in serv,addr struct hostent $server The error() function is identical to that in the ser er, as are the ariables sock'd# portno, and n. The ariable serv,addr will contain the address of the ser er to which we want to connect. +t is of type struct sockaddr<in. The ariable server is a pointer to a structure of type hostent. This structure is defined in the header file netd).h as follows! struct hostent { char $h,name /$ o''icial name o' host $/ char $$h,aliases /$ alias list $/ int h,addrtype /$ host address type $/ int h,length /$ length o' address $/ char $$h,addr,list /$ list o' addresses 'rom name server $/ #de'ine h,addr h,addr,list%=& /$ address# 'or )ack(ard compati)lity $/ "

12

Note that h,addr is an alias for the first address in the array of network addresses. char )u''er%*5+& i' (argc < D) { 'print'(stderr#5usage Cs hostname port5# argv%=&) e!it(=) " portno 8 atoi(argv%*&) sock'd 8 socket(-.,/012# 97:;,9261-<# =) i' (sock'd < =) error(516676 opening socket5) All of this code is the same as that in the ser er. server 8 gethost)yname(argv%1&) i' (server 88 0EFF) { 'print'(stderr#516676# no such host5) e!it(=) " The ariable argvF"G contains the name of a host on the +nternet, e.g. cs.rpi.edu. The function! struct hostent $gethost)yname(char $name) Takes such a name as an argument and returns a pointer to a hostent containing information about that host. The field char $h,addr contains the +3 address.+f this structure is N:,,, the system could not locate a host with this name. )3ero((char $) >serv,addr# si3eo'(serv,addr)) serv,addr.sin,'amily 8 -.,/012 )copy((char $)serverG>h,addr#(char $)>serv,addr.sin,addr.s,addr#serverG>h,length)
13

serv,addr.sin,port 8 htons(portno) This code sets the fields in serv,addr. Much of it is the same as in the ser er. Oowe er, because the field serverG>h,addr is a character string, we use the function! void )copy(char $s1# char $s*# int length) which copies length bytes from s1 to s*. 2222 i' (connect(sock'd#>serv,addr#si3eo'(serv,addr)) < =) error(516676 connecting5) The connect function is called by the client to establish a connection to the ser er. +t takes three arguments, the socket file descriptor, the address of the host to which it wants to connect $including the port number%, and the siPe of this address. This function returns @ on success and 2" if it fails. Notice that the client needs to know the port number of the ser er, but it does not need to know its own port number. This is typically assigned by the system when connect is called. print'(5Hlease enter the messageB 5) )3ero()u''er#*5+) 'gets()u''er#*55#stdin) n 8 (rite(sock'd#)u''er#strlen()u''er)) i' (n < =) error(516676 (riting to socket5) )3ero()u''er#*5+) n 8 read(sock'd#)u''er#*55) i' (n < =) error(516676 reading 'rom socket5) print'(5Cs5#)u''er) return =

"

14

+t prompts the user to enter a message, uses 'gets to read the message from stdin, writes the message to the socket, reads the reply from the socket, and displays this reply on the screen.

15

Das könnte Ihnen auch gefallen