IO::Socket::INET provides TCP sockets, both the server and the client side.
For UDP support, please see IO::Socket::Async.
Here is an example of a very simplistic "echo" server that listens on
my = IO::Socket::INET.new( :listen,:localhost<localhost>,:localport(3333) );loop
And a client that connects to it, and prints out what the server answers:
my = IO::Socket::INET.new( :host<localhost>,:port(3333) );.print: 'Hello, Raku';say .recv;.close;
Please bear in mind that this is a synchronous connection; an attempt by any of the nodes to write without the other reading will produce an
Could not receive data from socket: Connection reset by peer error.
multi method new(:,:,: = PF_INET,: = 'utf-8',: = "\r\n",--> IO::Socket::INET)multi method new(:,:,: = PF_INET,:,: = 'utf-8',: = "\r\n",--> IO::Socket::INET)
Creates a new socket.
:$listen is True, creates a new socket that listen on
:$localhost (which can be an IP address or a domain name) on port
:$localport; in other words the
:$listen flag determines the server mode of the socket. Otherwise (i.e.,
False), the new socket opens immediately a connection to
:$host on port
:$family defaults to
PF_INET constant for IPv4, and can be set to
PF_INET6 constant for IPv6.
Returns a lazy list of lines read from the socket.
In listen/server mode, waits for a new incoming connection. Once a new connection is established, an
IO::Socket::INET instance (or a subclass instance) for consuming the connection is returned.