Interview Questions

Simple programs that communicate with sockets The Receiver

Perl, Sockets and TCP/IP Networking


(Continued from previous question...)

Simple programs that communicate with sockets The Receiver

The first thing we need to do is to create a socket. We will use it to receive connections. The code below shows how to create a receiving socket. Note that we need to specify the local hostname and the port to which the socket will be bound. Of course, if the port is already in use this call will fail. Also note the 'Listen' parameter: this is the maximum number of connections that can be queued by the socket waiting for you to accept and process them. For the time being we will only accept a maximum of one connection at any time. (This means that a connection attempt while we're dealing with another connection, will return with an error like 'connection refused') Finally the 'Reuse' option tells the system to allow reuse of the port after the program exits. This is to ensure that if our program exits abnormally and does not properly close the socket, running it again will allow opening a new socket on the same port.

 1 use IO::Socket;
 2 my $sock = new IO::Socket::INET (
 3          LocalHost => 'thekla',
 4            LocalPort => '7070',
 5                Proto => 'tcp',
 6                  Listen => 1,
 7                   Reuse => 1,
 8                                 );
 9 die "Could not create socket:
     $!\n" unless $sock;

Now the socket is ready to receive incoming connections. To wait for a connection, we use the accept() method which will return a new socket through which we can communicate with the calling program. Information exchange is achieved by reading/writing on the new socket. The socket can be treated like a regular filehandle.

10 my $new_sock = $sock->accept();
11 while(<$new_sock>) {
12    print $_;
13 }
14 close($sock);

(Continued on next question...)

Other Interview Questions