使用简单TCP服务器保持持续连接

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();
2个回答

0
我认为你可能想要在所有消息前面加上某种包含消息长度的标头。例如,如果你要发送字符串“hello”,你可以在前面加上数字“5”,以便让另一端知道需要读取多少个字节。

0
如何在不重新打开连接的情况下保持发送和接收?
您在第一次接收-发送循环后立即关闭了连接。我希望您能理解,这会导致连接被关闭。
不要这样做。不要关闭连接。循环读取,直到检测到另一端已关闭。您可以通过将read的返回值与零进行比较来检测它。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接