Writing Simple Servers

This section is devoted to those aspects of Berkeley sockets and UNIX/WIN32 that support writing server code.  It contains only the essential calls.  We will learn more system calls later as we develop more complex client/server applications.

Unix/WIN32 systems calls that support the writing of server code

There are a number of UNIX and WIN32 system calls that you should know in order to write server code.   We will start with just one call.  More will be added later.

Select System Call

The select system call allows you to wait for multiple events on several sockets/file descriptors.  For example, you can determine if there is incoming data, if a connection request is pending, or if the pipe associated with a socket is able to take data.  The call is the same on both UNIX and WIN32 with the exception that on WIN32, the first argument is ignored.  If you ever expect to port your code always put in a valid value for the first argument.  I will insist on it for our class.  The following is the format for the call.

 

select

The select function determines the status of one or more sockets, waiting if necessary, to perform synchronous I/O.

int select(
  int nfds,                           
  fd_set FAR *readfds,               
  fd_set FAR *writefds,              
  fd_set FAR *exceptfds,             
  const struct timeval FAR *timeout  
);

Parameters

nfds
[in] Ignored. The nfds parameter is included only for compatibility with Berkeley sockets.   For UNIX it is the highest numbered socket plus 1.  In class we will talk about representation issues.
readfds
[in, out] Optional pointer to a set of sockets to be checked for readability.
writefds
[in, out] Optional pointer to a set of sockets to be checked for writability
exceptfds
[in, out] Optional pointer to a set of sockets to be checked for errors.
timeout
[in] Maximum time for select to wait, provided in the form of a TIMEVAL structure. Set the timeout parameter to NULL for blocking operation.

Return Values

The select function returns the total number of socket handles that are ready and contained in the fd_set structures, zero if the time limit expired, or SOCKET_ERROR if an error occurred. Note: this is currently the same as -1 which is what UNIX returns.  Why should I not use -1?  If the return value is SOCKET_ERROR, WSAGetLastError can be used to retrieve a specific error code.

Error code Meaning
WSANOTINITIALISED A successful WSAStartup call must occur before using this function.
WSAEFAULT The Windows Sockets implementation was unable to allocate needed resources for its internal operations, or the readfds, writefds, exceptfds, or timeval parameters are not part of the user address space.
WSAENETDOWN The network subsystem has failed.
WSAEINVAL The time-out value is not valid, or all three descriptor parameters were NULL.
WSAEINTR A blocking Windows Socket 1.1 call was canceled through WSACancelBlockingCall.
WSAEINPROGRESS A blocking Windows Sockets 1.1 call is in progress, or the service provider is still processing a callback function.
WSAENOTSOCK One of the descriptor sets contains an entry that is not a socket.

Remarks

The select function is used to determine the status of one or more sockets. For each socket, the caller can request information on read, write, or error status. The set of sockets for which a given status is requested is indicated by an fd_set structure. The sockets contained within the fd_set structures must be associated with a single service provider. For the purpose of this restriction, sockets are considered to be from the same service provider if the WSAPROTOCOL_INFO structures describing their protocols have the same providerId value. Upon return, the structures are updated to reflect the subset of these sockets that meet the specified condition. The select function returns the number of sockets meeting the conditions. A set of macros is provided for manipulating an fd_set structure. These macros are compatible with those used in the Berkeley software, but the underlying representation is completely different.

The parameter readfds identifies the sockets that are to be checked for readability. If the socket is currently in the listen state, it will be marked as readable if an incoming connection request has been received such that an accept is guaranteed to complete without blocking. For other sockets, readability means that queued data is available for reading such that a call to recv, WSARecv, WSARecvFrom, or recvfrom is guaranteed not to block.

For connection-oriented sockets, readability can also indicate that a request to close the socket has been received from the peer. If the virtual circuit was closed gracefully, and all data was received, then a recv will return immediately with zero bytes read. If the virtual circuit was reset, then a recv will complete immediately with an error code such as WSAECONNRESET. The presence of OOB data will be checked if the socket option SO_OOBINLINE has been enabled (see setsockopt).

The parameter writefds identifies the sockets that are to be checked for writability. If a socket is processing a connect call (nonblocking), a socket is writeable if the connection establishment successfully completes. If the socket is not processing a connect call, writability means a send, sendto, or WSASendto are guaranteed to succeed. However, they can block on a blocking socket if the len parameter exceeds the amount of outgoing system buffer space available. It is not specified how long these guarantees can be assumed to be valid, particularly in a multithreaded environment.

The parameter exceptfds identifies the sockets that are to be checked for the presence of OOB data (see section DECnet Out-of-band data for a discussion of this topic) or any exceptional error conditions.

Important  OOB data will only be reported in this way if the option SO_OOBINLINE is FALSE. If a socket is processing a connect call (nonblocking), failure of the connect attempt is indicated in exceptfds (application must then call getsockopt SO_ERROR to determine the error value to describe why the failure occurred). This document does not define which other errors will be included.

Any two of the parameters, readfds, writefds, or exceptfds, can be given as NULL. At least one must be non-NULL, and any non-NULL descriptor set must contain at least one handle to a socket.

Summary: A socket will be identified in a particular set when select returns if:

readfds:

writefds:

exceptfds:

Four macros are defined in the header file Winsock2.h for manipulating and checking the descriptor sets. The variable FD_SETSIZE determines the maximum number of descriptors in a set. (The default value of FD_SETSIZE is 64, which can be modified by defining FD_SETSIZE to another value before including Winsock2.h.) Internally, socket handles in an fd_set structure are not represented as bit flags as in Berkeley Unix. Their data representation is opaque. Use of these macros will maintain software portability between different socket environments. The macros to manipulate and check fd_set contents are:

FD_CLR(s, *set)
Removes the descriptor s from set.
FD_ISSET(s, *set)
Nonzero if s is a member of the set. Otherwise, zero.
FD_SET(s, *set)
Adds descriptor s to set.
FD_ZERO(*set)
Initializes the set to the NULL set.

The parameter time-out controls how long the select can take to complete. If time-out is a NULL pointer, select will block indefinitely until at least one descriptor meets the specified criteria. Otherwise, time-out points to a TIMEVAL structure that specifies the maximum time that select should wait before returning. When select returns, the contents of the TIMEVAL structure are not altered. If TIMEVAL is initialized to {0, 0}, select will return immediately; this is used to poll the state of the selected sockets. If select returns immediately, then the select call is considered nonblocking and the standard assumptions for nonblocking calls apply. For example, the blocking hook will not be called, and Windows Sockets will not yield.

The time value structure is defined as follows:

typedef struct timeval {
  long tv_sec;
  long tv_usec;
} timeval;

Note  The select function has no effect on the persistence of socket events registered with WSAAsyncSelect or WSAEventSelect

Example: in class we will write code to send out 10 daytime requests and to read and display them as soon as they come in.  I gave something like this on the first quiz when the course was last taught.

The following is a link to the example in the state we left it in at the end of class on 2/15 DayTime20.cpp

 

We need to add disconnect logic, dealing with partial messages.   How could we modify connectTCP to deal with errors in a more civilized way?

 

At this point we will go back to our original daytime client and get it working in UNIX.   Even if you are not a UNIX programmer, this will give you a perspective on getting this code working on another operating system.

 

We will also demonstrate the daytime client written in the .net environment.

System Calls Needed for Writing Servers

 

Review of functions needed to write server code.  That is socket, bind, listen, accept, read, write, close.  The following are some details on those calls that we have not discussed in detail.  I will use the shorter descriptions given by the UNIX man pages.  Keep in mind that "int socket" translates into "SOCKET socket" on the PC.

 

Bind

Associates a local IP address and a port with a socket.  This allows an application to advertise itself.

#include <sys/Winsock2.h>
int bind ( int socket, const struct sockaddr *address, socklen_t address_len );

socket - the socket created by the socket call.

address - an IP address of this system and a port number to be advertised.  Why the IP address?  A machine can have more than 1 IP addresses.  We can specify that the application will accept connections from all networks.  See example for more on the creation of this address.

address_len - the length of the address in bytes.  This is for the usual reason.

Returns 0 if successful and SOCKET_ERROR (-1 for UNIX)  if an error.  The following are some of the more significant errors.

 

WSAEADDRINUSE - the port is already used by another application.  (No WSA in the UNIX naming for this error)

 

WSAEACCES - the program does not have permission to use the address specified.  (No WSA in the UNIX naming for this error)  How could this happen?  Answer: you have specified a reserved port number.  Note: the spelling of the define for this error is correct.  I have no idea why they left off the last "S".  (We can blame UNIX for this.)

 

Remind everyone that it your server application goes down and then immediately up, that you will get the WSAEADDRINUSE error if you immediately try to bind to the original server port.

 

Listen

Tells the operating system that our application is ready to receive connections.

#include <sys/Winsock2.h>
int listen (int socket, int backlog );

sockets - bound socket created by socket call.
backlog - the size of the queue of connection requests.  See help page or man page for for how this value is interpreted.  Windows has
SOMAXCONN to indicate that you want the maximum "reasonable" backlog.

Returns 0 if successful and SOCKET_ERROR (-1 for UNIX) if fails.

Accept

Used to accept the next connection request.  Blocks if one is not pending.  We can make this non-blocking if we want to.  (Later)

#include <sys/Winsock2.h>

int accept ( int socket, struct sockaddr *address, socklen_t *address_len );

sockets - bound socket created by socket call.

address - returns the address of the client.

address_len - the length of the client address.

Returns SOCKET_ERROR (-1 for UNIX) if fails and the socket number of the connection to the client otherwise.

Example.  This is an example of a DAYTIME server.  Note: we are not allowed to use the official port number for this service.  The function passiveTCP will be of great use in the future. The following link is to a date sever program that runs on the PC. ServerDate.cpp  Note: the error processing is wrong.  I am using perror again How do we fix it?

 

Mention about bcopy and bzero which were found in older versions on this code.  So, if you have an older version of the text you might see these.

 

Having the address of the client can be useful for security.

Lab2  

Write an echo server.  This program should work for multiple client at the same time.  Use select to achieve concurrency.  You will also get rid of perror if you use my code.

 

This lab is a bit complicated so we will discuss it in class.

 

As an exercise in class, we will port this server to UNIX.