Chario0z
Chario0z

Reputation: 21

Perl - Sending multiple data through sockets

There's a thing I'm wondering about when it comes to socket programming in Perl. I'm trying to send two variabels through my socket. It works, I can send both but I want to receive them one by one. Let me show you my code and the output I get:

SERVER

my $var1 = 200;
chomp($var1);
$socket->send($var1);

my $var2 = 300;
chomp($var2);
$socket->send($var2);

CLIENT

$socket->recv(my $var1, 4000);
chomp($var1);
$socket->recv(my $var2, 4000);
chomp($var2);

print "From server: My height is: $var1 cm, weight is: $var2 kg\n";

Well, my expected output should be: From server: My height is: 400 cm, weight is: 300 cm. Instead, my output looks like this: From server: My height is: 400300 cm, weight is:

Well, I can't see why my code is wrong. Shouldnt I be able to receive data one by one like this? How would I eventually fix this to receive the data correctly?

Upvotes: 2

Views: 946

Answers (1)

pilcrow
pilcrow

Reputation: 58741

Short answer: Use datagram sockets or implement a communication protocol that delimits distinct messages.

You ask:

Shouldnt I be able to receive data one by one like this?

You can do that easily on datagram sockets like UDP: IO::Socket::INET->new(Type => SOCK_DGRAM, ...). There the writer/reader protocol is transmitting and receiving discrete packets of data, and send/recv will do what you want.

Stream sockets like TCP, on the other hand, have a continuous bytestream model. Here you need some sort of record separator or initial transmission of message size or similar. I suspect tis is what you are using.

Stream sockets are not unlike plain files, which appear as "bytestream" IO handles. If a file contained the string "300400", without any newlines, how would a reader of that file know that this string was actually two records instead of one (or six or five or an incomplete record, etc.)?

Upvotes: 2

Related Questions