Broad Network


Perl Socket Coding Basics

Internet Sockets and Perl – Part 3

Writing a Perl Module

Foreword: Perl comes with a module, called Socket. This module has functions for creating and using sockets. In this part of the series, I show you the basics on how to write Perl socket code (program). I use a client-server example.

By: Chrysanthus Date Published: 18 Oct 2014

Introduction

This is part 3 of my series, Internet Sockets and Perl. Perl comes with a module, called Socket. This module has functions for creating and using sockets. In this part of the series, I show you the basics on how to write Perl socket code (program). I use a client-server example. You should have read the previous parts of the series before reaching here, as this is a continuation. To use the socket module, you would type at the top of the script,

    use Socket;

You will use the console to try each of the code samples. In the Windows operating system, the console is the Command Prompt window found in the Accessories group of the Start Menu. The first code sample is for the client and the second is for the server. You will use local host (same computer) for the demonstration. If you are using Windows, you will need two command prompt windows, one for the server and one for the client.

I first explain the code samples before I tell you exactly what to do to demonstrate communication, between client socket and server socket.

Activity
The server socket program is started first. Next the client socket program is started. The client sends the message, “I love you.” to the server. The server responds by sending the message “I love you too.” to the client and closes its socket. The client displays this reply and also closes its socket.

While the socket of the server is not closed, because the accept() function is waiting to confirm a connection, you do not see the new DOS prompt at the console of the server.

With socket programming, the two programs at the ends of the channel can be in the same computer or in different computers. In many situations they are in different computers. In this demonstration exercise, they are in the same physical computer (localhost).

The Socket Client Code
The code is:

use strict;
use Socket;

    my ($iaddr, $paddr, $proto);
    
    $proto   = getprotobyname("tcp");
    $iaddr = gethostbyname("localhost");
    $paddr   = sockaddr_in(55555, $iaddr);
    socket(SOCK, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
    connect(SOCK, $paddr) || die "connect: $!";

    send (SOCK, "I love you.", 0);

    my $strC;
    recv (SOCK, $strC, 20, 0);
    print $strC, "\r\n";
    
    close (SOCK) || die "close: $!";

If you are not using the Windows Operating System, then begin the code with something like, #!/usr/bin/perl . You can save the file with the name clientSock.pl in c:\.

The second statement in the first code segment brings in the Socket module with its functions. After that in the code, you have declaration of the $iaddr, $paddr and $proto variables. There are two main sockets in the scheme: the client socket and the server socket. $iaddr is for the IP address of the server (remote socket). $paddr is for the packed address of the remote socket; and $proto is for the protocol of the channel, used by both the local and remote sockets.

Next in the code, the gethostbyname() function converts the domain name of the remote socket into the corresponding IP address. This function has to access the Internet if necessary. The next statement uses the IP address of the remote host and the port number of the remote host, to form the packed address of the remote host (server socket and remote socket here, mean the same thing).

The next statement creates the local socket. If the socket() function here fails, an error message will be displayed at the console. The error message developed is stored in the special Perl variable, $! . Next in the code the connection is made from the local socket to the remote socket (server socket). If this connect() function fails, the error message stored as a result, in the $! Variable, will be displayed at the console.

For a successful connection, the send() function sends the text "I love you." to the remote program. Everything being fine, the remote program (server) replies the message. It is actually a remote socket of the remote program that receives the message. The next code segment in the client program uses the recv() function to receive and display the reply from the server.

The last statement in the client program closes the socket and releases system resources. If the close() function fails, the error message developed and stored in the $! variable is displayed. It is not good for the close() function to fail, because if it fails, the computer recourses will not be released and other programs in the computer will operate slowly or stop operating because of scarcity of system resources. If resources are not released for whatever reason, the obvious way to get them back is to reboot the computer.

Note: if the socket() or the connect() or the close() function fails, the error message developed by Perl, is stored in the $! variable. Also note that all the functions in the client or server program are from the Socket module.

The Socket Server Code
The code is:

use strict;
use Socket;
     
    my $proto = getprotobyname("tcp");
    
    socket(Server, PF_INET, SOCK_STREAM, $proto) || die "socket: $!";
    my $iaddr = gethostbyname("localhost");
    my $paddr   = sockaddr_in(55555, $iaddr);
    bind(Server, $paddr) || die "bind: $!";
    listen(Server, 5) || die "listen: $!";
    
    
    my $str;
    accept(NewSOCK,Server);
    recv (NewSOCK,$str,11,0);
    if ($str eq "I love you.")
        {
                send (NewSOCK, "I love you too.", 0);
        }


    close (NewSOCK) || die "close: $!";
    close (Server) || die "close: $!";

If you are not using the Windows Operating System, then begin the code with something like, #!/usr/bin/perl . You can save this file with the name serverSock.pl in c:\.

The getprotobyname() function obtains the protocol name suitable for the socket() function. The gethostbyname() and sockaddr_in() functions are for the server host. Here the server host is the localhost. Here the server socket, is the local socket, while the remote socket is the client socket. Here, the sockaddr_in() function takes as arguments, the port number and IP address of the localhost. Here, the IP address may not be exactly the figure number.

So, for a simple client code, you need the packed address for the remote socket and you do not need the packed address for the local socket. For a simple server code, you need the packed address for the local (server) socket and you do not really need the packed address for the remote (client) socket.

In the server code high up, the socket for the server is created (opened). This is the local socket so far as the server is concerned. If this function fails, the error message stored as a result, in the $! Perl special variable, is displayed at the console of the server. In the code the socket (filehandle) for the server is called, Server.  

Assuming that the socket creation is successful, in the server code, you should have next the binding function. This function associates the server socket to the packed address of the server socket, to form a solid endpoint.

Next in the server code, you have the listen() function that listens for an incoming connection, hopefully from a client. It needs the server socket filehandle for this. It is not the listen() function that accepts a connection. If the creation of this action fails, the error message stored as a result, in the $! Perl special variable, will be displayed at the console of the server.

Assuming that all the socket functions in the server code have operated successfully, you should in the coding, have the accept function. This is a very important function. It accepts a connection by creating a new socket, in this case called, NewSOCK. It needs the mother (generic) socket, Server for this. It is NewSOCK that will continue communication with the socket at the other end (client). It is this function that gives rise to the flashing underscore at the server console to show that a process is going on and every other thing for the console should wait. When the accept function completes its mission, the flashing underscore stops and you will see the new DOS prompt. If this function fails to execute, false is returned, but that has not been taken care of in this simple server program.

The server code can then go on to receive (with the recv() function) any message from the client connected; it needs the new socket filehandle to do this (and continue communication with the client socket). You should read through the code.

Every socket opened most be closed. At the end of the server program, the new and the mother sockets are closed. Use is made of the $! special variable.

Demonstrating Socket Action
In this illustration, the client and server socket programs are in the same computer. You do not need any other program for these two programs to communicate with one another. You need only a good operating system and the Perl interpreter.

To test the program, open a console (command prompt) for the server and lunch serverSock.pl, using DOS commands. You should see a flashing underscore. Next open another console for the client and lunch clientSock.pl. You should see “I love you too.” displayed shortly. The client produces “I love you.” and the server produces “I love you too.” if it receives “I love you.” from the client.

Immediately after the client program is lunched, both programs interact and you will see the new DOS prompt for each of the console as the two programs go to an end.

Length for recv Function
In the above client code, the maximum number of bytes received by the recv function is 20. It is possible for the string sent by the server to be more than 20 bytes. In this case, you use the following code segment for the recv and print functions:

    do
        {
            recv (SOCK, $strC, 20, 0);
            print $strC, "\r\n";
        }while (length($strC) == 20);

Continuous Sending and Receiving
With the above scheme, in order to send text again and then receive reply, you have to create a socket with a new name and then repeat the typing of the connect, send and recv functions. At the server, you also have to repeat the typing of the accept, recv and send functions.

It is possible to design the client and the server programs such that, at the client, one socket is created and one connection is made, then you can have a sequence of send and recv functions. To achieve this, just replace all occurrences of NewSOCK at the server program, with Server, and place the accept code segment in a while loop.

At this point, I hope you see that socket programming is not difficult. It is the documentations out there that are difficult to understand. This tutorial set is not difficult to understand.

End of Series
It has been an easy ride, based on some good previous knowledge. Perl socket programming is not as difficult as it seemed. You have now discovered a good learning source, for the issue. Perl socket programming looks difficult elsewhere because the documentation is not good (there). Here the documentation is good and that is why the learning process has been good. Remember, in this blog, you always need to have the pre-knowledge to swim (easily understand) through the current tutorials or articles.

You should have completed this series and understood. This is therefore your stepping stone to understand how to produce a Perl database driver (API) and how to produce a Perl web server. The next series to learn in this volume is “Writing a PurePerl MySQL Driver”. You can use the search box above to arrive at the series.

That is it for this part of the series.

Chrys

Related Links

Internet Sockets and Perl
Perl pack and unpack Functions
Writing MySQL Protocol Packets in PurePerl
Developing a PurePerl MySQL API
Using the PurePerl MySQL API
Database
Perl Course
MySQL Course
More Related Links
Perl Mailsend
PurePerl MySQL API
Perl Course - Professional and Advanced
Major in Website Design
Web Development Course
Producing a Pure Perl Library
MySQL Course

BACK

Comments

Become the Writer's Fan
Send the Writer a Message