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

时间:2014-07-21 16:53:32

标签: 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 => '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 :(得分:0)

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

答案 1 :(得分:0)

  

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

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

不要这样做。不要关闭连接。读入循环,直到检测到另一侧已关闭。通过比较read的返回值和零来检测它。