The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Net::EasyTCP - Easily create TCP/IP clients and servers via an OO interface and event callbacks

SYNOPSIS

SERVER EXAMPLE:

  use Net::EasyTCP;

  $server = new Net::EasyTCP(
        mode            =>      "server",
        port            =>      2345,
        )
        || die "ERROR CREATING SERVER: $@\n";

  $server->callback(
        data            =>      \&gotdata,
        connect         =>      \&connected,
        disconnect      =>      \&disconnected,
        )
        || die "ERROR SETTING CALLBACKS: $@\n";

  $server->start() || die "ERROR STARTING SERVER: $@\n";

  sub gotdata() {
        my $client = shift;
        my $serial = $client->serial();
        my $data = $client->data();
        print "Client $serial sent me some data, sending it right back to them again\n";
        $client->send($data) || die "ERROR SENDING TO CLIENT: $@\n";
        if ($data eq "QUIT") {
                $client->close() || die "ERROR CLOSING CLIENT: $@\n";
                }
        elsif ($data eq "DIE") {
                $server->stop() || die "ERROR STOPPING SERVER: $@\n";
                }
        }

  sub connected() {
        my $client = shift;
        my $serial = $client->serial();
        print "Client $serial just connected\n";
        }

  sub disconnected() {
        my $client = shift;
        my $serial = $client->serial();
        print "Client $serial just disconnected\n";
        }

CLIENT EXAMPLE:

  use Net::EasyTCP;

  $client = new Net::EasyTCP(
        mode            =>      "client",
        host            =>      'localhost',
        port            =>      2345,
        )
        || die "ERROR CREATING CLIENT: $@\n";

  #Send and receive a simple string
  $client->send("HELLO THERE") || die "ERROR SENDING: $@\n";
  $reply = $client->receive() || die "ERROR RECEIVING: $@\n";

  #Send and receive complex objects/strings/arrays/hashes by reference
  %hash = ("to be or" => "not to be" , "just another" => "perl hacker");
  $client->send(\%hash) || die "ERROR SENDING: $@\n";
  $reply = $client->receive() || die "ERROR RECEIVING: $@\n";
  foreach (keys %{$reply}) {
        print "Received key: $_ = $reply->{$_}\n";
        }

  #Send and receive large binary data
  for (1..4096) {
        for (0..255) {
                $largedata .= chr($_);
                }
        }
  $client->send($largedata) || die "ERROR SENDING: $@\n";
  $reply = $client->receive() || die "ERROR RECEIVING: $@\n";

  $client->close();

DESCRIPTION

This class allows you to easily create TCP/IP clients and servers and provides an OO interface to manage the connection(s). This allows you to concentrate on the application rather than on the transport.

You still have to engineer your high-level protocol. For example, if you're writing an SMTP client-server pair, you will have to teach your client to send "HELO" when it connects, and you will have to teach your server what to do once it receives the "HELO" command, and so forth.

What you won't have to do is worry about how the command will get there, about line termination, about binary data, complex-structure serialization, or about fragmented packets on the received end. All of these will be taken care of by this class.

CONSTRUCTOR

new(%hash)

Constructs and returns a new Net::EasyTCP object. Such an object behaves in one of two modes (that needs to be supplied to new() on creation time). You can create either a server object (which accepts connections from several clients) or a client object (which initiates a connection to a server).

new() expects to be passed a hash. The following keys are accepted:

mode

Must be set to either "client" or "server" according to the type of object you want returned. (Mandatory)

port

Must be set to the port the client connects to (if mode is "client") or to the port to listen to (if mode is "server"). If you're writing a client+server pair, they must both use the same port number. (Mandatory)

host

Must be set to the hostname/IP address to connect to. (Mandatory when mode is "client")

METHODS

[C] = Available to objects created as mode "client"

[S] = Available to objects created as mode "server"

callback(%hash)

[S] Tells the server which subroutines to call when specific events happen. For example when a client sends the server data, the server calls the "data" callback sub.

callback() expects to be passed a hash. Each key in the hash is the callback type identifier, and the value is a reference to a sub to call once that callback type event occurs.

Valid keys in that hash are:

connect

Called when a new client connects to the server

data

Called when an existing client sends data to the server

disconnect

Called when an existing client disconnects

Whenever a callback sub is called, it is passed a single parameter, a CLIENT OBJECT. The callback code may then use any of the methods available to client objects to do whatever it wants to do (Read data sent from the client, reply to the client, close the client connection etc...)

close()

[C] Instructs a client object to close it's connection with a server.

data()

[C] Retrieves the previously-retrieved data associated with a client object. This method is typically used from inside the callback sub associated with the "data" event, since the callback sub is passed nothing more than a client object.

disconnect()

See close()

mode()

[C][S] Identifies the mode of the object. Returns either "client" or "server"

receive()

[C] Receives data sent to the client by a server and returns it. It will block until data is received or until 300 seconds of inactivity have elapsed.

running()

[S] Returns true if the server is running (started), false if it is not.

send($data)

[C] Sends data to a server. It can be used on client objects you create with the new() constructor, or with client objects passed to your callback subs by a running server.

It accepts one parameter, and that is the data to send. The data can be a simple scalar or a reference to something more complex.

serial()

[C] Retrieves the serial number of a client object, This is a simple integer that allows your callback subs to easily differentiate between different clients.

start()

[S] Starts a server and does NOT return until the server is stopped via the stop() method. Once a server is started it will accept new client connections as well as parse incoming data from clients and fire off the appropriate callbacks' subs.

stop()

[S] Instructs a running server to stop and returns immediately (does not wait for the server to actually stop, which may be a few seconds later). To check if the server is still running or not use the running() method.

RETURN VALUES AND ERRORS

The constructor and all methods return something that evaluates to true when successful, and to false when not successful.

The only exception to the above rule is the data() method. If the data received is an empty string or the string "0" then it will evaluate to false which is probably not what you want. In that case check that the data you just read is defined.

If not successful, the variable $@ will contain a description of the error that occurred.

NOTES

Internal Protocol

This class implements a miniature protocol when it sends and receives data between it's clients and servers. This means that a server created using this class cannot properly communicate with a normal client of any protocol (pop3/smtp/etc..) unless that client was also written using this class. It also means that a client written with this class will not properly communicate with a different server (telnet/smtp/pop3 server for example, unless that server is implemented using this class also). This limitation may change in future releases.

In other words, if you write a server using this class, write the client using this class also, and vice versa.

Deadlocks

As with any client-server scenario, make sure you engineer how they're going to talk to each other, and the order they're going to talk to each other in, quite carefully. If both ends of the connection are waiting for the other end to say something, you've got a deadlock.

TO DO

  • Make the client object work with other servers not written with this class, and vice versa. (automatic protocol detection)

  • Implement optional compression. (transparently compress and decompress client-server communications)

  • Implement optional encryption. (transparently secure client-server communications)

AUTHOR

Mina Naguib, mnaguib@cpan.org

SEE ALSO

IO::Socket