3

Using this simple TCP server/client example in perl, how can I keep sending and receiving without having to reopen the connection (continuously receive data, and process it as it arrives)?

Server:

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

Client:

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();
DexterGold
  • 31
  • 2

2 Answers2

0

I think what you probably want is to prefix all of your messages with some sort of header that contains the length of the message. For example, if you're sending the string hello on the wire, you might prefix with the number 5 to let the other end know how many bytes to read.

Vinbot
  • 518
  • 2
  • 14
0

how can I keep sending and receiving without having to reopen the connection

You are closing the connection immediately after the first receive-send cycle. I hope it kind of makes sense to you that this causes the connection ... to be closed.

Don't do that. Don't close the connection. Read in a loop until you detect that the other side has shut down. You detect that by comparing the return value of read with zero.

usr
  • 168,620
  • 35
  • 240
  • 369