Interview Questions

Simple programs that communicate with sockets: The Caller

Perl, Sockets and TCP/IP Networking


(Continued from previous question...)

Simple programs that communicate with sockets: The Caller

The other side of the communication is even simpler. All we need to do is to create a socket specifying the remote address and port. The constructor will return a socket object after the connection has been etablished, and we may start sending data right away by writing onto the socket like any other filehandle.

 1 use IO::Socket;
 2 my $sock = new IO::Socket::INET (
 3                         PeerAddr => 'asomatos',
 4                         PeerPort => '7070',
 5                         Proto => 'tcp',
 6                                 );
 7 die "Could not create socket: $!\n" unless $sock;
 8 print $sock "Hello there!\n";
 9 close($sock);

You can easily try out the example programs above. All you need to do is execute the receiver first and then the sender. On the receiver end, you will see the line "Hello there!" printed on the terminal screen. If you do not have a network, you can still use 'localhost' for the hostname of both the receiver and caller just to test it out.

Synchronization

An important issue to consider in this style of communication is that the two ends must follow a commonly-agreed procedure of data exchange. Otherwise it is very easy to end up in a deadlock situation where either both ends try to read, or both ends try to write. Ther is no way to guess whether the other end has finshed sending data, unless there is some protocol of communication between them that denotes logical sections of the communication in the contents of the transmitted messages. In the example above, the model is very simplistic: The caller sends a message and closes its end of the connection, while the receiver just reads the data until it's all finished.

Usually client-server transactions consist of a caller (the client) sending a request, followed by the receiver (server) sending back a reply. In order for the server to understand when the request is finished, there is some agreed marker (such as two consecutive empty lines, or a line saying "END REQUEST") that denotes the last line in the request. The server, starts sending its reply only after this line has been received, and afterwards closes the socket. The receiver, after sending the entire request switches to reading until the socket is closed, so it will receive the reply. More complex schemes can be established in a similar mannere, according to your needs and taste. What is important is to make sure that the two ends of the communication have a way of knowing when to speak and when to listen, thus avoiding the possibility of getting locked up.

(Continued on next question...)

Other Interview Questions