【问题标题】:Keep open socket connection Perl保持打开的套接字连接 Perl
【发布时间】:2018-02-11 20:21:50
【问题描述】:

我创建了一个在我的服务器上打开一个新套接字的 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 localhost 9000
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
e //(Sent)
e //(Received)
Connection closed by foreign host.

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

【问题讨论】:

  • 不是问题,但是当您的数据包含非数字字符时,您需要使用eq,而不是==
  • 是的,我知道。我把它固定在我的机器上。
  • 您有什么建议可以解决我的问题吗? @simbabque
  • edit 然后更新问题。总是向我们展示你的真实代码,这样你就不会在一个不属于你的问题上浪费别人的时间;)
  • 接受后,你读了一些东西,写了一些东西,然后你在循环中的块就完成了。这意味着客户端文件描述符超出了关闭套接字的范围。如果你想在同一个连接上多次读写,你必须围绕这个读写循环。

标签: perl sockets network-programming


【解决方案1】:

我在我的代码中添加了一个循环,它起作用了! 感谢@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();
        }
    }

【讨论】:

  • 不需要外部循环,因为您专门exit 程序,所以它只会建立一个连接。
猜你喜欢
  • 1970-01-01
  • 2012-11-23
  • 2018-02-25
  • 2013-04-19
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 2012-02-02
  • 1970-01-01
相关资源
最近更新 更多