3

在 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();
4

2 回答 2

0

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

您将在第一个接收发送周期后立即关闭连接。我希望这对您来说是有意义的,这会导致连接...关闭。

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

于 2014-07-22T20:44:38.023 回答
0

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

于 2014-07-21T17:05:11.613 回答