Fortran

Guide To Learn

The complete client program

The following listing provides the complete program for the Fortran TCP client.

Listing 11.9 Fortran TCP client–the complete program

program client
 
  use iso_c_binding, only: c_int, c_char, c_null_char, c_size_t, &
                           c_int64_t, c_carriage_return, c_new_line
  use mod_dill, only: ipaddr, ipaddr_remote, IPADDR_IPV4, &
                      mrecv, tcp_connect, suffix_attach
 
  implicit none
  integer :: i
  integer(c_int) :: rc, connection
  integer(c_size_t) :: message_size, msglen = 64
  type(ipaddr) :: addr
  character(c_char) :: message(64) = ''
  character(len=*), parameter :: &
    TCP_SUFFIX = c_carriage_return // c_new_line // c_null_char
 
  rc = ipaddr_remote(addr, '127.0.0.1' // c_null_char, 5555_c_int, &
                     IPADDR_IPV4, -1_c_int64_t)
  connection = tcp_connect(addr, -1_c_int64_t)
  connection = suffix_attach(connection, TCP_SUFFIX, 2_c_size_t)
  message_size = mrecv(connection, message, msglen, -1_c_int64_t)
  print *, message_size, message
 
end program client

If you now recompile the client program and run it again (making sure the server is still running in the other terminal), you’ll see a familiar greeting message:

./client
                    5 Hello

The first item in the output (the numeral 5) is the length of the message (correct!), and the second item is the message itself: “Hello.” This is proof that both our client and server work, as the message was transferred correctly using the TCP protocol, even if on the same machine. You can try this exercise on separate computers, and it will still work if the IP address and port number of the server are publicly accessible from the internet.

If you want to take this one step further as an exercise, consider adapting the client and server programs with the get_command_argument subroutine, described in chapter 10, to allow these programs to receive the IP address and port number as command-line arguments.

Note You can download the complete code for this chapter from https:// github.com/modern-fortran/tcp-client-server.

The complete client program

Leave a Reply

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

Scroll to top