Fortran

Guide To Learn

TCP server program: Receiving network connections

Perhaps the best advice is just to be careful. Don’t type things in you don’t understand. Debugging takes too much time. Have a mental picture (or a real drawing) of how your C code is using memory. That’s good advice in any language, but in C it’s critical.

 –Nick Parlante, Essential C

Although this quote applies specifically to writing C code (which we won’t do here), it’s nevertheless important to keep in mind as we go forward with writing the Fortran-C interface.

We’ll start by implementing the TCP server first. The heavy lifting of opening and listening on sockets, sending and receiving messages, and the TCP protocol itself will be handled internally by libdill and the operating system, so we won’t have to worry about the implementation details of these pieces. What we’ll focus on is correctly implementing the Fortran interfaces with libdill functions, and understanding what they do.

Our server will perform the following steps:

  1. Initialize the IP address data structure.
  2. Open a socket on a given IP address and port number.
  3. Listen patiently for incoming connections.
  4. On an incoming connection, send a message to the client.
  5. When done, close the connection and move on.

To implement each step, we’ll write Fortran interfaces with the appropriate C functions (figure 11.3):

  • ipaddr_local–Initialize the data structure that holds the IP address and port number for the local computer (server).
  • tcp_listen–Create a new socket given the input IP address structure and listen for incoming connections to it.
  • tcp_accept–Accept an incoming connection on a socket.
  • suffix_attach and suffix_detach–Append/remove a character string to/from all messages on a given connection to conform to a specific protocol, in our case TCP (not shown in figure 11.3).

Figure 11.3 Fortran TCP server program, illustrated

  • msend–Send a message to the remote client that just connected to the server.
  • tcp_close–Gracefully close the connection and move on.

As you can see in figures 11.2 and 11.3, ipaddr_local and tcp_listen will be invoked once, when the server program starts up. tcp_accept and msend will be in an infinite do loop, to allow accepting connections one after another, indefinitely. suffix_attach and suffix_detach, while not included in the figures for brevity, are convenience functions that will help us format our character strings into valid TCP messages.

We’ll tackle these one at a time and learn Fortran-C interoperability along the way. Let’s go in order.

TCP server program: Receiving network connections

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top