How to write simple TCP server and client in Perl

If you want to create a server and client which communicate with each other via TCP, there are many ways to implement it. In this post, I will show you a simple TCP server and client example written in Perl.

In this example, client connects to a server with well-known IP address and port. Once client is connected to the server, it sends data to the server, and waits for a reply. Upon receiving data from client, server responds with an acknowledgement message.

The purpose of shutdown(SOCKET, 1) in the example is to tell the other end that you have finished sending data, without closing SOCKET. Note that you can still receive data afterward.

TCP server example in Perl

use IO::Socket::INET;

# auto-flush on socket
$| = 1;

# creating a listening socket
my $socket = new IO::Socket::INET (
    LocalHost => '',
    LocalPort => '7777',
    Proto => 'tcp',
    Listen => 5,
    Reuse => 1
die "cannot create socket $!\n" unless $socket;
print "server waiting for client connection on port 7777\n";

    # waiting for a new client connection
    my $client_socket = $socket->accept();

    # get information about a newly connected client
    my $client_address = $client_socket->peerhost();
    my $client_port = $client_socket->peerport();
    print "connection from $client_address:$client_port\n";

    # read up to 1024 characters from the connected client
    my $data = "";
    $client_socket->recv($data, 1024);
    print "received data: $data\n";

    # write response data to the connected client
    $data = "ok";

    # notify client that response has been sent
    shutdown($client_socket, 1);


TCP client example in Perl

use IO::Socket::INET;

# auto-flush on socket
$| = 1;

# create a connecting socket
my $socket = new IO::Socket::INET (
    PeerHost => '',
    PeerPort => '7777',
    Proto => 'tcp',
die "cannot connect to the server $!\n" unless $socket;
print "connected to the server\n";

# data to send to a server
my $req = 'hello world';
my $size = $socket->send($req);
print "sent data of length $size\n";

# notify server that request has been sent
shutdown($socket, 1);

# receive a response of up to 1024 characters from server
my $response = "";
$socket->recv($response, 1024);
print "received response: $response\n";


Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

Support Xmodulo

Did you find this tutorial helpful? Then please be generous and support Xmodulo!

The following two tabs change content below.
Dan Nanni is the founder and also a regular contributor of He is a Linux/FOSS enthusiast who loves to get his hands dirty with his Linux box. He likes to procrastinate when he is supposed to be busy and productive. When he is otherwise free, he likes to watch movies and shop for the coolest gadgets.

9 thoughts on “How to write simple TCP server and client in Perl

  1. Any way we can do in python?
    I was thinking of setting up a jabber server for communication! Is that a bad idea?

    • I meant I earlier thought that setting up an xmpp communication is a way to communicate messages from sever to a client!
      This script does an awesome job of doing so. Just had to ask if the same can be done in python.
      Sure the script gets the work done! But there are things like encrypting it and then decrypting it on the other side. I don't mean some obvious options like add 1 char to the words and send, then remove the same. Maybe something of ssh kind of security. Just gave a thought! Though much useless :O


      • Sure, writing such server/client in python should be straightforward. I guess it's for another post. :-)

        As for message encryption, it's easy. Just use IO::Socket::SSL, instead of plain socket as in the example.

  2. Can any one help me regarding perl socket creation, and sending an XMl request (header and body) and reading response.

    Thanks in advance

  3. excellent! thank you for the short-n-sweet tutorial.
    The next step is to use perl's Parallel::ForkManager module to fork off into child processes for each client connection that comes in.

  4. Thanks for this simple code. I've tried a lot of such examples and this was the first one that ran out-of-the box (after I changed the connection address in the client to - as I ran both scripts on the same machine). I also was able to connect to a python server example script, that is equally simple:

    #!/usr/bin/env python
    import socket
    TCP_IP = ''
    TCP_PORT = 7777
    BUFFER_SIZE = 1024  # Normally 1024, but we want fast response
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind((TCP_IP, TCP_PORT))
    print "server waiting for client connection on port 7777"
    while 1:
        conn, addr = s.accept()
        print 'Connection address:', addr
        data = conn.recv(BUFFER_SIZE)
        if not data: break
        if data == "SHUTDOWN":
            conn.send("server shutting down on client request - good bye!")
        print "received data:", data
        print "echo-ing back..."
        conn.send(data)  # echo
  5. Hi Dan,

    there's one problem with this simple example: If the client is permanently communicating with the server, it will create and destroy the socket very often. After thousands of calls, socket creation fails. I added a wait-and-retry loop and recognized, that socket creation only fails sometimes for some 20..30 seconds. Then it suddenly works fine for minutes until again, there's this period, where it sometimes fails. I assume, that the socket is not properly destroyed (on system level - because on Perl level, when $socket goes out of scope, it should be garbage collected).

    Could you please add code that shows, how the client socket can be generated only once, and then re-used over and over?

    • I assume the problem here is not the proper destruction of the socket. If you use a pair of sockets, the ephemeral one at client side and the "well-known" one at server side, to set up a TCP session, and then close that session, TCP mandates a certain guard time before you can re-use the same pair of sockets again. The "well-known" port at server side is a single one, and the pool of ports at client side which can be used to establish sessions is limited.

      So the symptoms you describe suggest that as you keep establishing a new session each time you "open the socket", over time you exhaust the available pool of ports completely, and those 20..30 seconds have to elapse before the oldest client-side port becomes available for new use for a session to the same server.

      The remedy here would be to keep the "socket" at client side open (and, therefore, use the same TCP session all the time) and re-use it for data transfer.

Leave a comment

Your email address will not be published. Required fields are marked *