Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Perl 与简单TCP服务器的持久连接_Perl_Sockets_Tcp_Io Socket - Fatal编程技术网

Perl 与简单TCP服务器的持久连接

Perl 与简单TCP服务器的持久连接,perl,sockets,tcp,io-socket,Perl,Sockets,Tcp,Io Socket,在perl中使用这个简单的TCP服务器/客户机示例,如何在不重新打开连接的情况下继续发送和接收数据(连续接收数据,并在数据到达时进行处理) 服务器: use IO::Socket::INET; # auto-flush on socket $| = 1; # creating a listening socket my $socket = new IO::Socket::INET ( LocalHost => '0.0.0.0', LocalPort => '77

在perl中使用这个简单的TCP服务器/客户机示例,如何在不重新打开连接的情况下继续发送和接收数据(连续接收数据,并在数据到达时进行处理)

服务器:

use IO::Socket::INET;

# auto-flush on socket
$| = 1;

# creating a listening socket
my $socket = new IO::Socket::INET (
    LocalHost => '0.0.0.0',
    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";

while(1)
{
    # 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";
    $client_socket->send($data);

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

$socket->close();
客户:

use IO::Socket::INET;

# auto-flush on socket
$| = 1;

# create a connecting socket
my $socket = new IO::Socket::INET (
    PeerHost => '192.168.1.10',
    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";

$socket->close();

我认为您可能想要的是在所有消息的前面加上某种包含消息长度的头。例如,如果您要在线路上发送字符串
hello
,则可以使用数字
5
作为前缀,让另一端知道要读取多少字节

如何在不重新打开连接的情况下继续发送和接收

您将在第一个接收-发送周期后立即关闭连接。我希望这对你来说是有意义的,因为这导致了联系。。。待关闭

不要那样做。不要关闭连接。在循环中读取,直到检测到另一端已关闭。您可以通过比较read的返回值与零来检测