Search code examples
perlsocketsnetwork-programming

Keep open socket connection Perl


I created a Perl script that opens a new socket on my server. When I connect with telnet to the socket and I write (and receive) something, the connection closes.

#!/usr/bin/perl
use strict;
use warnings;
use IO::Socket;
use IO::Socket::INET;
$| = 1;
my $sock = IO::Socket::INET->new(Listen    => 5,
                                 LocalAddr => 'localhost',
                                 LocalPort => 9000,
                                 Reuse => 1,
                                 Proto     => 'tcp');
die "Socket not created $!\n" unless $sock;
print "Server waiting for connections\n";
while(1)
{
    # waiting for a new client connection
    my $client_socket = $sock->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);
    chomp($data);
    print "Data: $data\n";

    # write response data to the connected client
    my $dataok = "OK";
    $client_socket->send("$dataok\n");
    $client_socket->send("$data\n");
    if($data == 500){
        close($sock);
        exit(); 
    }
    elsif($data eq "Close\r") {
        close($sock);
        exit();
    }
}

My telnet session:

telnet localhost 9000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
e //(Sent)
e //(Received)
Connection closed by foreign host.

Why does my script close the connection? Thanks in advance


Solution

  • I added a loop in my code and it worked! Thanks to @simbabque and @SteffenUllrich.

        # waiting for a new client connection
        my $client_socket = $sock->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
        while(1){
            my $data = "";
            $client_socket->recv($data, 1024);
            chomp($data);
            print "Data: $data\n";
    
            # write response data to the connected client
            my $dataok = "OK";
            $client_socket->send("$dataok\n");
            $client_socket->send("$data\n");
            if($data == 500){
                close($sock);
                exit(); 
            }
            elsif($data eq "Close\r") {
                close($sock);
                exit();
            }
        }