保持打开套接字连接Perl

时间:2018-02-11 11:11:11

标签: perl sockets network-programming

我创建了一个Perl脚本,在我的服务器上打开一个新的套接字。 当我用telnet连接到套接字并写入(并接收)某些东西时,连接就会关闭。

#!/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();
    }
}

我的telnet会话:

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

为什么我的脚本会关闭连接? 提前致谢

1 个答案:

答案 0 :(得分:5)

我在代码中添加了一个循环并且它有效! 感谢@simbabque和@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();
        }
    }