📄 2.t
字号:
An error is returned if the connection was unsuccessful(any name automatically bound by the system, however, remains).Otherwise, the socket is associated with the server anddata transfer may begin. Some of the more common errors returnedwhen a connection attempt fails are:.IP ETIMEDOUT.brAfter failing to establish a connection for a period of time,the system decided there was no point in retrying theconnection attempt any more. This usually occurs becausethe destination host is down, or because problems inthe network resulted in transmissions being lost..IP ECONNREFUSED.brThe host refused service for some reason.This is usuallydue to a server processnot being present at the requested name..IP "ENETDOWN or EHOSTDOWN".brThese operational errors are returned based on status information delivered tothe client host by the underlying communication services..IP "ENETUNREACH or EHOSTUNREACH".brThese operational errors can occur either because the networkor host is unknown (no route to the network or host is present),or because of status information returned by intermediategateways or switching nodes. Many times the status returnedis not sufficient to distinguish a network being down from ahost being down, in which case the systemindicates the entire network is unreachable..PPFor the server to receive a client's connection it must performtwo steps after binding its socket.The first is to indicate a willingness to listen forincoming connection requests:.DSlisten(s, 5);.DEThe second parameter to the \fIlisten\fP call specifies the maximumnumber of outstanding connections which may be queued awaiting acceptance by the server process; this numbermay be limited by the system. Should a connection berequested while the queue is full, the connection will not berefused, but rather the individual messages which comprise therequest will be ignored. This gives a harried server time to make room in its pending connection queue while the clientretries the connection request. Had the connection been returnedwith the ECONNREFUSED error, the client would be unable to tellif the server was up or not. As it is now it is still possibleto get the ETIMEDOUT error back, though this is unlikely. Thebacklog figure supplied with the listen call is currently limitedby the system to a maximum of 5 pending connections on anyone queue. This avoids the problem of processes hogging systemresources by setting an infinite backlog, then ignoringall connection requests..PPWith a socket marked as listening, a server may \fIaccept\fPa connection:.DSstruct sockaddr_in from; ...fromlen = sizeof (from);newsock = accept(s, (struct sockaddr *)&from, &fromlen);.DE(For the UNIX domain, \fIfrom\fP would be declared as a\fIstruct sockaddr_un\fP, and for the NS domain, \fIfrom\fPwould be declared as a \fIstruct sockaddr_ns\fP,but nothing different would needto be done as far as \fIfromlen\fP is concerned. In the exampleswhich follow, only Internet routines will be discussed.) A newdescriptor is returned on receipt of a connection (along witha new socket). If the server wishes to find out who its client is,it may supply a buffer for the client socket's name. The value-resultparameter \fIfromlen\fP is initialized by the server to indicate howmuch space is associated with \fIfrom\fP, then modified on returnto reflect the true size of the name. If the client's name is notof interest, the second parameter may be a null pointer..PP\fIAccept\fP normally blocks. That is, \fIaccept\fPwill not return until a connection is available or the system callis interrupted by a signal to the process. Further, there is noway for a process to indicate it will accept connections from onlya specific individual, or individuals. It is up to the user processto consider who the connection is from and close down the connectionif it does not wish to speak to the process. If the server processwants to accept connections on more than one socket, or wants to avoid blockingon the accept call, there are alternatives; they will be consideredin section 5..NH 2Data transfer.PPWith a connection established, data may begin to flow. To sendand receive data there are a number of possible calls.With the peer entity at each end of a connectionanchored, a user can send or receive a message without specifyingthe peer. As one might expect, in this case, thenthe normal \fIread\fP and \fIwrite\fP system calls are usable,.DSwrite(s, buf, sizeof (buf));read(s, buf, sizeof (buf));.DEIn addition to \fIread\fP and \fIwrite\fP,the new calls \fIsend\fP and \fIrecv\fPmay be used:.DSsend(s, buf, sizeof (buf), flags);recv(s, buf, sizeof (buf), flags);.DEWhile \fIsend\fP and \fIrecv\fP are virtually identical to\fIread\fP and \fIwrite\fP,the extra \fIflags\fP argument is important. The flags,defined in \fI<sys/socket.h>\fP, may bespecified as a non-zero value if one or moreof the following is required:.DS.TSl l.MSG_OOB send/receive out of band dataMSG_PEEK look at data without readingMSG_DONTROUTE send data without routing packets.TE.DEOut of band data is a notion specific to stream sockets, and onewhich we will not immediately consider. The option to have datasent without routing applied to the outgoing packets is currently used only by the routing table management process, and isunlikely to be of interest to the casual user. The abilityto preview data is, however, of interest. When MSG_PEEKis specified with a \fIrecv\fP call, any data present is returnedto the user, but treated as still \*(lqunread\*(rq. Thatis, the next \fIread\fP or \fIrecv\fP call applied to the socket willreturn the data previously previewed..NH 2Discarding sockets.PPOnce a socket is no longer of interest, it may be discardedby applying a \fIclose\fP to the descriptor,.DSclose(s);.DEIf data is associated with a socket which promises reliable delivery(e.g. a stream socket) when a close takes place, the system willcontinue to attempt to transfer the data. However, after a fairly long period oftime, if the data is still undelivered, it will be discarded.Should a user have no use for any pending data, it may perform a \fIshutdown\fP on the socket prior to closing it.This call is of the form:.DSshutdown(s, how);.DEwhere \fIhow\fP is 0 if the user is no longer interested in readingdata, 1 if no more data will be sent, or 2 if no data is tobe sent or received..NH 2Connectionless sockets.PPTo this point we have been concerned mostly with sockets whichfollow a connection oriented model. However, there is alsosupport for connectionless interactions typical of the datagramfacilities found in contemporary packet switched networks.A datagram socket provides a symmetric interface to dataexchange. While processes are still likely to be clientand server, there is no requirement for connection establishment.Instead, each message includes the destination address..PPDatagram sockets are created as before.If a particular local address is needed,the \fIbind\fP operation must precede the first data transmission.Otherwise, the system will set the local address and/or portwhen data is first sent.To send data, the \fIsendto\fP primitive is used,.DSsendto(s, buf, buflen, flags, (struct sockaddr *)&to, tolen);.DEThe \fIs\fP, \fIbuf\fP, \fIbuflen\fP, and \fIflags\fPparameters are used as before. The \fIto\fP and \fItolen\fPvalues are used to indicate the address of the intended recipient of themessage. Whenusing an unreliable datagram interface, it isunlikely that any errors will be reported to the sender. Wheninformation is present locally to recognize a message that cannot be delivered (for instance when a network is unreachable),the call will return \-1 and the global value \fIerrno\fP willcontain an error number. .PPTo receive messages on an unconnected datagram socket, the\fIrecvfrom\fP primitive is provided:.DSrecvfrom(s, buf, buflen, flags, (struct sockaddr *)&from, &fromlen);.DEOnce again, the \fIfromlen\fP parameter is handled ina value-result fashion, initially containing the size ofthe \fIfrom\fP buffer, and modified on return to indicatethe actual size of the address from which the datagram was received..PPIn addition to the two calls mentioned above, datagramsockets may also use the \fIconnect\fP call to associatea socket with a specific destination address. In this case, anydata sent on the socket will automatically be addressedto the connected peer, and only data received from thatpeer will be delivered to the user. Only one connectedaddress is permitted for each socket at one time;a second connect will change the destination address,and a connect to a null address (family AF_UNSPEC)will disconnect.Connect requests on datagram sockets return immediately,as this simply results in the system recordingthe peer's address (as compared to a stream socket, where aconnect request initiates establishment of an end to endconnection). \fIAccept\fP and \fIlisten\fP are notused with datagram sockets..PPWhile a datagram socket socket is connected,errors from recent \fIsend\fP calls may be returnedasynchronously.These errors may be reported on subsequent operationson the socket,or a special socket option used with \fIgetsockopt\fP, SO_ERROR,may be used to interrogate the error status.A \fIselect\fP for reading or writing will return truewhen an error indication has been received.The next operation will return the error, and the error status is cleared.Other of the lessimportant details of datagram sockets are describedin section 5..NH 2Input/Output multiplexing.PPOne last facility often used in developing applicationsis the ability to multiplex i/o requests among multiplesockets and/or files. This is done using the \fIselect\fPcall:.DS#include <sys/time.h>#include <sys/types.h> ...fd_set readmask, writemask, exceptmask;struct timeval timeout; ...select(nfds, &readmask, &writemask, &exceptmask, &timeout);.DE\fISelect\fP takes as arguments pointers to three sets, one forthe set of file descriptors for which the caller wishes tobe able to read data on, one for those descriptors to whichdata is to be written, and one for which exceptional conditionsare pending; out-of-band data is the onlyexceptional condition currently implemented by the socketIf the user is not interestedin certain conditions (i.e., read, write, or exceptions),the corresponding argument to the \fIselect\fP shouldbe a null pointer..PPEach set is actually a structure containing an array oflong integer bit masks; the size of the array is setby the definition FD_SETSIZE.The array is belong enough to hold one bit for each of FD_SETSIZE file descriptors..PPThe macros FD_SET(\fIfd, &mask\fP) andFD_CLR(\fIfd, &mask\fP)have been provided for adding and removing file descriptor\fIfd\fP in the set \fImask\fP. Theset should be zeroed before use, andthe macro FD_ZERO(\fI&mask\fP) has been providedto clear the set \fImask\fP.The parameter \fInfds\fP in the \fIselect\fP call specifies the rangeof file descriptors (i.e. one plus the value of the largestdescriptor) to be examined in a set. .PPA timeout value may be specified if the selectionis not to last more than a predetermined period of time. Ifthe fields in \fItimeout\fP are set to 0, the selection takesthe form of a\fIpoll\fP, returning immediately. If the last parameter isa null pointer, the selection will block indefinitely*..FS* To be more specific, a return takes place only when adescriptor is selectable, or when a signal is received bythe caller, interrupting the system call..FE\fISelect\fP normally returns the number of file descriptors selected;if the \fIselect\fP call returns due to the timeout expiring, thenthe value 0 is returned.If the \fIselect\fP terminates because of an error or interruption,a \-1 is returned with the error number in \fIerrno\fP,and with the file descriptor masks unchanged..PPAssuming a successful return, the three sets willindicate whichfile descriptors are ready to be read from, written to, orhave exceptional conditions pending.The status of a file descriptor in a select mask may betested with the \fIFD_ISSET(fd, &mask)\fP macro, whichreturns a non-zero value if \fIfd\fP is a member of the set\fImask\fP, and 0 if it is not..PPTo determine if there are connections waiting on a socket to be used with an \fIaccept\fP call,\fIselect\fP can be used, followed bya \fIFD_ISSET(fd, &mask)\fP macro to check for readreadiness on the appropriate socket. If \fIFD_ISSET\fPreturns a non-zero value, indicating permission to read, then aconnection is pending on the socket..PPAs an example, to read data from two sockets, \fIs1\fP and\fIs2\fP as it is available from each and with a one-secondtimeout, the following codemight be used:.DS#include <sys/time.h>#include <sys/types.h> ...fd_set read_template;struct timeval wait; ...for (;;) { wait.tv_sec = 1; /* one second */ wait.tv_usec = 0; FD_ZERO(&read_template); FD_SET(s1, &read_template); FD_SET(s2, &read_template); nb = select(FD_SETSIZE, &read_template, (fd_set *) 0, (fd_set *) 0, &wait); if (nb <= 0) { \fIAn error occurred during the \fPselect\fI, or the \fPselect\fI timed out.\fP } if (FD_ISSET(s1, &read_template)) { \fISocket #1 is ready to be read from.\fP } if (FD_ISSET(s2, &read_template)) { \fISocket #2 is ready to be read from.\fP }}.DE.PPIn 4.2, the arguments to \fIselect\fP were pointers to integersinstead of pointers to \fIfd_set\fPs. This type of callwill still work as long as the number of file descriptorsbeing examined is less than the number of bits in aninteger; however, the methods illustrated above shouldbe used in all current programs..PP\fISelect\fP provides a synchronous multiplexing scheme.Asynchronous notification of output completion, input availability,and exceptional conditions is possible through use of theSIGIO and SIGURG signals described in section 5.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -