tags:

views:

40

answers:

3

I have a Client-Server Perl program. I want to send a message stored in an array to the server.

Server code:

use IO::Socket::INET;

# Creating a a new socket
$socket=new IO::Socket::INET->new(LocalPort=>5000,Proto=>'udp');

print "\nUDPServer Waiting for client on port 5000";

while(1)
{
    $socket->recv($recieved_data,1024);
    $peer_address = $socket->peerhost();
    $peer_port = $socket->peerport();
    print "\n($peer_address , $peer_port) said : $recieved_data";
}

Client code::

use IO::Socket::INET;

# Create a new socket
$socket=new IO::Socket::INET->new(PeerAddr=>'127.0.0.1',PeerPort=>5000,Proto=>'udp');

@message_array = ("message", 120, "sample");
$socket->send(@message_array);

In server side I changed like,

$socket->recv(@recieved_data,1024);

But I am getting an error like this,

UDPServer Waiting for client on port 5000usage: $sock->recv(BUF, LEN [, FLAGS]) at udp_server.pl line 17

How to send an array and getting it printed or displayed in the server side.?

+1  A: 

You can't send an array directly. Serialize your array with pack/unpack if you have simple strings or use Storable for a more general solution.

igelkott
+2  A: 

send/recv in IO::Socket::INET are merely inherited from IO::Socket. From POD:

IO::Socket::INET provides an object interface to creating and using sockets in the AF_INET domain. It is built upon the IO::Socket interface and inherits all the methods defined by IO::Socket.

IO::Socket in turn a front end around built-in Perl functions of the same names.

As we can see for send ( http://search.cpan.org/~jesse/perl-5.12.2/pod/perlfunc.pod ).

send SOCKET,MSG,FLAGS

    Sends a message on a socket. 
    Attempts to send the **scalar** MSG to the SOCKET filehandle. 

Those functions explicitly only take a scalar message, so you need to somehow serialize the array into a scalar.

You can either use your own serialization protocol (comma-join the string if the members of array are guaranteed not to have commas inside strings, as one example); or use packings; or use Data::Dumper->Dump or Storable or any other serialization package you prefer. If you would like to compare different methods, you can research "perl serialize".

DVK
+2  A: 

You have to serialize the data. You send the serialized chunk of data over the wire then unserialize it.

There are many options for this. The Indonesian Perl mongers recently made a comparison of serialization modules

Perl comes with Storable, which can work just fine although you have to be careful that the module hasn't changed in some way so that one version's serialization works with another version.

There are data formats such as YAML or JSON that might be better since they don't depend on module versions. Both can handle complex data structures, although YAML can deal with Perl objects and JSON can't (although JSYNC can). Each option has different trade-offs.

brian d foy