gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 02:43:39 24 4
gpt4 key购买 nike

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

最佳答案

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

关于perl - 与简单 TCP 服务器的持久连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24870491/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com