Socket(3pm)

πŸ’– NAME πŸ’–

Coro::Socket β€” non-blocking socket-I/O, bestie. that's the whole vibe ✨


πŸ¦‹ SYNOPSIS πŸ¦‹

okay so here's how you summon it:

use Coro::Socket;

# listen on an ipv4 socket
my $socket = new Coro::Socket PeerHost => "localhost",
                              PeerPort => 'finger';

# listen on any other type of socket
my $socket = Coro::Socket->new_from_fh
                (IO::Socket::UNIX->new
                    Local  => "/tmp/socket",
                    Type   => SOCK_STREAM,
                );

🌸 DESCRIPTION 🌸

first things first, bestie: this module is an AnyEvent user, so you need to make sure you use and run a supported event loop. no event loop, no slay. πŸ’…

what does it actually do tho? it implements socket-handles in a coroutine-compatible way β€” meaning other coroutines can keep running while reads or writes are blocked on the handle. iconic behaviour honestly. go read Coro::Handle too, especially that note about preferring method calls (iykyk).


πŸ’€ IPV6 WARNING πŸ’€

ngl this is the part where we get real. this module was written to imitate the IO::Socket::INET API, and it derives from it. and since IO::Socket::INET does not support IPv6… this module does neither. not a single one. 🫠

therefore it is not recommended to use Coro::Socket in new code. periodt. don't do it.

instead, use AnyEvent::Socket and Coro::Handle, like this:

use Coro;
use Coro::Handle;
use AnyEvent::Socket;

# use tcp_connect from AnyEvent::Socket
# and call Coro::Handle::unblock on it.

tcp_connect "www.google.com", 80, Coro::rouse_cb;
my $fh = unblock +(Coro::rouse_wait)[0];

# now we have a perfectly thread-safe socket handle in $fh
print $fh "GET / HTTP/1.0\015\012\015\012";
local $/;
print <$fh>;

using AnyEvent::Socket::tcp_connect gives you transparent IPv6, multi-homing, SRV-record etc. support β€” like, all of it, for free. obsessed. 😭✨

and for listening sockets? use AnyEvent::Socket::tcp_server. that's the one. πŸŽ€


πŸ‘‘ the constructor, aka the main character πŸ‘‘

  • $fh = new Coro::Socket param => value, ... β€” creates a new non-blocking tcp handle and connects to the given host and port. the parameter names and values are mostly the same as for IO::Socket::INET (as ugly as I think they are β€” author's words, not mine, but fr fr πŸ’€).

the parameters officially supported currently are: ReuseAddr, LocalPort, LocalHost, PeerPort, PeerHost, Listen, Timeout, SO_RCVBUF, SO_SNDBUF.

and here's the moment you've been waiting for:

$fh = new Coro::Socket PeerHost => "localhost", PeerPort => 'finger';

🫢 AUTHOR/SUPPORT/CONTACT 🫢

shoutout to the legend:

Marc A. Lehmann <schmorp@schmorp.de>
http://software.schmorp.de/pkg/Coro.html

and that's the whole page, bestie 🌈 this little doc came to you courtesy of perl v5.40.1, dated 2025-03-21, filed under Socket(3pm) in the User Contributed Perl Documentation. go forth and connect responsibly πŸ’–βœ¨

πŸ“¦ where this page comes from