EasyTCP(3pm)

πŸ“¦
version 0.26 Β· 2 versions
, in ubuntu jammy

πŸ’– NAME πŸ’–

Net::EasyTCP β€” bestie, this is the module that lets you spin up secure, bandwidth-friendly TCP/IP clients and servers without losing your entire mind. It's EasyTCP(3pm), from the User Contributed Perl Documentation corner of the universe, and it's lowkey iconic.


✨ FEATURES ✨

  • 🫢 One single module that builds both clients and servers. One. Module. No cap.
  • πŸ‘‘ Fully Object Oriented interface β€” we love a classy queen.
  • πŸ”₯ Event-based callbacks when you're in server mode (she's reactive, she listens).
  • 🌈 An internal protocol that handles all the common transport problems for you so you literally never have to think about them.
  • πŸ”’ Transparent encryption β€” it just happens, you don't lift a finger.
  • πŸŽ€ Transparent compression β€” also just happens. Free glow-up for your packets.

🌸 SYNOPSIS 🌸

πŸ’… SERVER EXAMPLE:

use Net::EasyTCP;

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

#
# Tell it about the callbacks to call
# on known events
#
$server->setcallback(
        data            =>      \&gotdata,
        connect         =>      \&connected,
        disconnect      =>      \&disconnected,
)
|| die "ERROR SETTING CALLBACKS: $@\n";

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

#
# This sub gets called when a client sends us data
#
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";
        }
}

#
# This sub gets called when a new client connects
#
sub connected {
        my $client = shift;
        my $serial = $client->serial();
        print "Client $serial just connected\n";
}

#
# This sub gets called when an existing client disconnects
#
sub disconnected {
        my $client = shift;
        my $serial = $client->serial();
        print "Client $serial just disconnected\n";
}

πŸ¦‹ CLIENT EXAMPLE:

use Net::EasyTCP;

#
# Create a new client and connect to a server
#
$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..8192) {
        for (0..255) {
                $largedata .= chr($_);
        }
}
$client->send($largedata) || die "ERROR SENDING: $@\n";
$reply = $client->receive() || die "ERROR RECEIVING: $@\n";

#
# Cleanly disconnect from the server
#
$client->close();

πŸ¦‹ DESCRIPTION πŸ¦‹

Okay so here's the tea β˜• β€” this class lets you build TCP/IP clients and servers so easily, and it hands you a whole OO interface to manage your connection(s). The entire point is that you get to focus on your actual application instead of babysitting the transport layer. Periodt.

⚠️ heads up bestie: you still have to engineer your own high-level protocol. Like, if you're writing an SMTP client-server pair, you have to teach your client to send "HELO" when it connects, and teach your server what to do once it receives that "HELO" command, and so on and so forth. That part is on you. πŸ’…

But what you will not have to worry about, ever, is: how the command actually gets there, line termination, binary data, complex-structure serialization, encryption, compression, or fragmented packets on the received end. This class is handling all of that. All of it. Every crumb. πŸ“


πŸŽ€ CONSTRUCTOR πŸŽ€

new(%hash)

Constructs and returns a brand new Net::EasyTCP object, and she slays. Such an object behaves in one of two modes β€” and yes, you have to tell new() which one at creation time. You can either make a server object (which accepts connections from several clients) or a client object (which initiates a connection to a server). Pick your fighter. πŸ‘‘

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

donotcheckversion

Set to 1 to force a client to keep connecting even if an encryption/compression/Storable module version mismatch gets detected.

🚨 Using this is HIGHLY unrecommended. You should upgrade the module in question to the same version on both ends, fr fr.

Not me telling you: as of Net::EasyTCP version 0.20, this parameter is fairly useless, because that version (and higher) do not require external modules to have the same version anymore β€” instead they determine compatability between different versions dynamically. See the accompanying Changes file for more details.

(Optional and acceptable when mode is "client")

donotcompress

Set to 1 to forcefully disable compression even if the appropriate module(s) are found. (Optional)

donotcompresswith

Set to a scalar or an arrayref of compression module(s) you'd like to avoid compressing with. For example, if you do not want to use Compress::LZF, you can do so by utilizing this option. (Optional)

donotencrypt

Set to 1 to forcefully disable encryption even if the appropriate module(s) are found. (Optional)

donotencryptwith

Set to a scalar or an arrayref of encryption module(s) you'd like to avoid encrypting with. For example, Crypt::RSA takes a long time to initialize keys and encrypt/decrypt, so you can avoid using it by utilizing this option. (Optional)

host

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

mode

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

password

Defines a password to use for the connection. When mode is "server", this password will be required from clients before the full connection is accepted. When mode is "client", this is the password that the server connecting to requires.

Also, when encryption using a symmetric encryption module is used, this password is included as part of the secret "key" for encrypting the data. (Optional)

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)

timeout

Set to an integer (seconds) that a client attempting to establish a TCP/IP connection to a server will timeout after. If not supplied, the default is 30 seconds. (Optional and acceptable only when mode is "client")

welcome

If someone uses an interactive telnet program to telnet to the server, they will see this welcome message. (Optional and acceptable only when mode is "server")

✨ METHODS ✨

Okay bestie, here's the method menu πŸ’…. First, the little tags that tell you who gets to use what:

  • [C] = Available to objects created as mode "client"
  • [H] = Available to "hybrid" client objects, as in "the server-side client objects created when a new client connects". These are the objects passed to your server's callbacks. Such hybrid clients behave almost exactly like a normal "client" object you create yourself, except for a slight difference in the available methods to retrieve data.
  • [S] = Available to objects created as mode "server"

addclientip(@array)

[S] Adds an IP address (or IP addresses) to the list of allowed clients to a server. If this is done, the server will not accept connections from clients not in it's list.

The compliment of this function is deleteclientip() .

callback(%hash)

See setcallback().

clients()

[S] Returns all the clients currently connected to the server. If called in array context will return an array of client objects. If called in scalar context will return the number of clients connected.

close()

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

compression()

[C][H] Returns the name of the module used as the compression module for this connection, undef if no compression occurs.

data()

[H] Retrieves the previously-retrieved data associated with a hybrid 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.

deleteclientip(@array)

[S] Deletes an IP address (or IP addresses) from the list of allowed clients to a server. The IP address (or IP addresses) supplied will no longer be able to connect to the server.

The compliment of this function is addclientip() .

disconnect()

See close().

do_one_loop()

[S] Instructs a server object to "do one loop" and return ASAP. This method needs to be called VERY frequently for a server object to function as expected (either through some sort of loop inside your program if you need to do other things beside serve clients, or via the start() method if your entire program is dedicated to serving clients). Each one loop will help the server do it's job, including accepting new clients, receiving data from them, firing off the appropriate callbacks etc.

encryption()

[C][H] Returns the name of the module used as the encryption module for this connection, undef if no encryption occurs.

mode()

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

receive($timeout)

[C] Receives data sent to the client by a server and returns it. It will block until data is received or until a certain timeout of inactivity (no data transferring) has occurred.

It accepts an optional parameter, a timeout value in seconds. If none is supplied it will default to 300.

remoteip()

[C][H] Returns the IP address of the host on the other end of the connection.

remoteport()

[C][H] Returns the port of the host on the other end of the connection.

running()

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

send($data)

[C][H] Sends data to a server. It can be used on client objects you create with the new() constructor, clients objects returned by the clients() method, 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()

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

setcallback(%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.

setcallback() 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...)

socket()

[C][H] Returns the handle of the socket (actually an IO::Socket object) associated with the supplied object. This is useful if you're interested in using IO::Select or select() and want to add a client object's socket handle to the select list.

⚠️ Note that eventhough there's nothing stopping you from reading and writing directly to the socket handle you retrieve via this method, you should never do this since doing so would definately corrupt the internal protocol and may render your connection useless. Instead you should use the send() and receive() methods.

start(subref)

[S] Starts a server and does NOT return until the server is stopped via the stop() method. This method is a simple while() wrapper around the do_one_loop() method and should be used if your entire program is dedicated to being a server, and does not need to do anything else concurrently.

If you need to concurrently do other things when the server is running, then you can supply to start() the optional reference to a subroutine (very similar to the callback() method). If that is supplied, it will be called every loop. This is very similar to the callback subs, except that the called sub will be passed the server object that the start() method was called on (unlike normal client callbacks which are passed a client object). The other alternative to performing other tasks concurrently is to not use the start() method at all and directly call do_one_loop() repeatedly in your own program.

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.


🌈 COMPRESSION AND ENCRYPTION 🌈

Clients and servers written using this class will automatically compress and/or encrypt the transferred data if the appropriate modules are found.

Compression will be automatically enabled if one (or more) of: Compress::Zlib or Compress::LZF are installed on both the client and the server.

As-symmetric encryption will be automatically enabled if Crypt::RSA is installed on both the client and the server.

Symmetric encryption will be automatically enabled if one (or more) of: Crypt::Rijndael* or Crypt::RC6* or Crypt::Blowfish* or Crypt::DES_EDE3* or Crypt::DES* or Crypt::Twofish2* or Crypt::Twofish* or Crypt::TEA* or Crypt::CipherSaber are installed on both the client and the server.

Strong randomization will be automatically enabled if Crypt::Random is installed; otherwise perl's internal rand() is used to generate random keys.

Preference to the compression/encryption method used is determind by availablity checking following the order in which they are presented in the above lists.

Note that during the negotiation upon connection, servers and clients written using Net::EasyTCP version lower than 0.20 communicated the version of the selected encryption/compression modules. If a version mismatch is found, the client reported a connection failure stating the reason (module version mismatch). This behavior was necessary since it was observed that different versions of the same module could produce incompatible output. If this is encountered, it is strongly recommended you upgrade the module in question to the same version on both ends, or more preferrably, Net::EasyTCP on both ends to the latest version, at a minimum 0.20. However, if you wish to forcefully connect overlooking a version mismatch (risking instability/random problems/data corruption) you may supply the "donotcheckversion" key to the new() constructor of the client object. This is no longer a requirement of Net::EasyTCP version 0.20 or higher since these newer versions have the ability to use different-version modules as long as their data was compatible, which was automatically determined at negotiation time.

To find out which module(s) have been negotiated for use you can use the compression() and encryption() methods.

  • Note that for this class's purposes, Crypt::CBC is a requirement to use any of the encryption modules with a * next to it's name in the above list. So eventhough you may have these modules installed on both the client and the server, they will not be used unless Crypt::CBC is also installed on both ends.
  • Note that the nature of symmetric cryptography dictates sharing the secret keys somehow. It is therefore highly recommend to use an As-symmetric cryptography module (such as Crypt::RSA) for serious encryption needs; as a determined hacker might find it trivial to decrypt your data with other symmetric modules.
  • Note that if symmetric cryptography is used, then it is highly recommended to also use the "password" feature on your servers and clients; since then the "password" will, aside from authentication, also be used in the "secret key" to encrypt the data. Without a password, the secret key has to be transmitted to the other side during the handshake, significantly lowering the overall security of the data.

If the above modules are installed but you want to forcefully disable compression or encryption, supply the "donotcompress" and/or "donotencrypt" keys to the new() constructor. If you would like to forcefully disable the use of only some modules, supply the "donotcompresswith" and/or "donotencryptwith" keys to the new() constructor. This could be used for example to disable the use of Crypt::RSA if you cannot afford the time it takes to generate it's keypairs etc...

πŸ’– RETURN VALUES AND ERRORS πŸ’–

okay so here's the tea on how this whole thing tells you if it worked or not:

the constructor and every single method return something that evaluates to true when it worked, and false when it didn't. that's it, that's the system. no cap.

but bestie, there are a couple of exceptions to that rule and they are these two methods right here:

  • clients()
  • data()

the way these two will straight up return something that evaluates to false β€” like an empty string, an empty array, or even the string "0" β€” even though nothing went wrong 😭. like it's not being shady, it's just built different. so in that case, don't panic, just check whether the value that came back is defined or not, using the defined() Perl function. that's the vibe check you need here.

and if something did actually go wrong? the variable $@ will be holding a description of the error that occurred. so go read it. it's trying to tell you something. 🫢


πŸ¦‹ NOTES πŸ¦‹

πŸ’€ Incompatability with Net::EasyTCP version 0.01

so version 0.02 and everything after it had their internal protocol modified to a fairly large degree. and the consequence of that is that compatability with version 0.01 is literally impossible now. gone. not coming back.

if you're gonna use version 0.02 or later (highly recommended, fr fr), then you need to make sure that none of the clients/servers are still running version 0.01. like, check. for real. and honestly? it is highly recommended to use the same version of this module on both sides. matching versions, matching energy. ✨

πŸ”’ Internal Protocol

this class implements a whole miniature protocol when it sends and receives data between its clients and servers. which means:

  • 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.
  • and a client written with this class will not properly communicate with a different server (a telnet/smtp/pop3 server for example, unless that server is implemented using this class also).

and this limitation is not going away in future releases, because the internal protocol gives us a plethora of advantages. it's giving main character energy and we're keeping it. πŸ‘‘

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

⏳ Delays

this class does not use the fork() method whatsoever. like, at all. which means all of its input/output and multi-socket handling is done via select().

and that leads to this limitation right here, so listen up: when a server calls one of your callback subs, it waits for it to return and therefore cannot do anything else. if your callback sub takes 5 minutes to return, then the server will not be able to do anything for 5 minutes β€” such as acknowledge new clients, or process input from other clients. five minutes of the whole thing just standing there. πŸ’€

in other words: make the code in your callbacks' subs' minimal and strive to make it return as fast as possible. in and out. quick little visit. 🧚

🚧 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. two besties both waiting for the other to text first. nobody texts. nothing happens. forever. 😭


πŸ‘‘ AUTHOR πŸ‘‘

Mina Naguib http://www.topfx.com mnaguib@cpan.org


🌈 SEE ALSO 🌈

Perl(1), IO::Socket, IO::Select, Compress::Zlib, Compress::LZF, Crypt::RSA, Crypt::CBC, Crypt::Rijndael, Crypt::RC6, Crypt::Blowfish, Crypt::DES_EDE3, Crypt::DES, Crypt::Twofish2, Crypt::Twofish, Crypt::TEA, Crypt::CipherSaber, Crypt::Random, defined(), rand()


Copyright (C) 2001-2003 Mina Naguib. All rights reserved. Use is subject to the Perl license.


and that's a wrap on EasyTCP(3pm), bestie!! πŸ¦‹βœ¨ this whole page is perl v5.24.1, dated 2016-09-13, and you made it all the way to the end β€” iconic behaviour, truly. go build something cute with it. mwah πŸ’…πŸ’–

πŸ“¦ where this page comes from