5.3. The listen() API call

Once we have a socket, and we've called bind() so that it's bound to a given port and address, we have to tell the system that we want to listen for connections.

The listen() API call is documented in IBM's manual at this location: http://publib.boulder.ibm.com/pubs/html/as400/v4r5/ic2924/info/apis/listen.htm

The manual tells us that the C language prototype for the listen() API looks like this:

                  int listen(int socket_descriptor,
                             int back_log);
     

This is an easy one. The RPG data type for an 'int' is 10I 0. This prototype accepts two integers, and returns an integer. Easy. Looks like this:

         D listen          PR            10I 0 ExtProc('listen')
         D   socket_desc                 10I 0 Value
         D   back_log                    10I 0 Value
     

All the listen() API does is tell the system that we're willing to accept incoming connections. In other words, it turns this socket into a 'server socket'.

The 'back_log' parameter tells the system how many clients will be queued up to wait for our server program. You can think of this as being similar to a print queue... In a print queue, each time a new report is created, it is placed into the queue. When the printer is ready to print, it takes the first report from the queue and prints it.

The back_log works the same way. When a client calls connect(), it gets put into our queue. If there are more than 'back_log' connections in our queue, the system sends back a 'Connection Refused' message to the client.

When we're ready to talk to the client, we call the accept() API, which takes the first connection off of the queue.

The listen API is quite simple to call:

         c                   if        listen(socket: 100) < 0
         c** listen() failed, check errno!
         c                   endif