Jeff Weisberg on Tue, 21 May 2002 00:00:17 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] perl and sockets


[...]
|     $client = $inet->accept();
|     while(my $block = <$client>) {
| 	  print_one($block);
|     }
| 
| Ah, but there's the rub. That read <$client> is looking for an EOL
| terminator, near as I can tell, but it probably won't get one, as what
| it's reading is binary.
| 
| In C, I'd use read, which I could do in perl, too. But I expect perl
| to be simpler for such a simple case. Am I missing something?

(NB: you didn't say, but I'm assuming this is a SOCK_STREAM (eg tcp)
socket, the answer will be different if it is SOCK_DGRAM (eg udp))


as you guessed, <> is looking for eol ($/ actually) which it
isn't going to find.

read (or sysread) is what you want. and since this is variable length,
to be correct, you'll want to do it in 2 reads, something like
(untested, and error handling elided):

	while(1){
		# get the char and the length field
		read $client, $buffer, 3;
		($c, $n) = unpack "cn", $buffer;
		# read in the specified amount of data
		read $client, $buffer, 12 * $n;
		@data = unpack "NNN" x $n, $buffer;
		# do something with data
	}

| As an aside, is there a simple way to unpack that data struct that
| comes across? I'm currently using a sequence of unpacks, the first to
| get the char and the short (N), then others to read the array of
| structs.

I might do it like I did above, or I might loop something like:

	while(1){
		# get the char and the length field
		read $client, $buffer, 3;
		($c, $n) = unpack "cn", $buffer;
		# read in the data in chunks
		foreach my $i (1 .. $n){
			read $client, $buffer, 12;
			($a, $b, $c) = unpack "NNN", $buffer;
			# do something with data
		}

depending on what I wanted to do with the data

| Thanks in advance for any tips. I'm a bit of a newbie for writing
| tcp/ip code.

If I was the one writing both ends of the code, I'd send newline delimited
ascii data, not binary data, as it'd be easier to code, and easier to debug.


	--jeff


______________________________________________________________________
Philadelphia Linux Users Group       -      http://www.phillylinux.org
Announcements-http://lists.phillylinux.org/mail/listinfo/plug-announce
General Discussion  -  http://lists.phillylinux.org/mail/listinfo/plug