4

I find at least 3 ways to read from a nonblocking socket in perl

$socket->recv
$socket->sysread
POSIX::read($socket,...

looks like 3 different names to the same thing, I read the documentations but I can't find one huge differente. anyone?

Tiago Peczenyj
  • 4,387
  • 2
  • 22
  • 35

2 Answers2

8

sysread is stream (TCP) oriented (it doesn't care about where one send ends and another begins), and recv is datagram (UDP) oriented (it does care).

POSIX::read works on file descriptors, whereas sysread works on file handles.

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • Correction: `recv` actually works fine with streams too. It might even be a better choice than `sysread`. `recv` is simply specific to sockets, while `sysread` works with all streams (e.g. it also works with plain files). – ikegami Jun 26 '19 at 17:20
  • See also: [What is the difference between `read` and `sysread`?](https://stackoverflow.com/q/36315124/589924) (Note that this is about the builtin `read`. `POSIX::read` is closer to `sysread`.) – ikegami Jun 26 '19 at 17:22
2

The best source for documentation on recv() is man recvfrom - it is basically a perl interface to that system call. Note that recv() is usually used on sockets which are set up non-connection oriented (i.e. a UDP socket), but it may be also be used on connection oriented (i.e. TCP) sockets.

The man differences between read(), sysread() and POSIX::read() are:

  • read(...) takes a file handle and the IO is buffered
  • sysread(...) takes a file handle and the IO is not buffered
  • POSIX::read(...) takes a file descriptor and the IO is not buffered

A file descriptor is a value (a small integer) that is returned by POSIX::open(). Also, you can get the file descriptor of a perl file handle via the fileno() function.

ErikR
  • 51,541
  • 9
  • 73
  • 124