perl function send
The send
function in Perl is used to send a message to a socket. Here's an example of using send
to send a message to a remote server:
use strict; use warnings; use IO::Socket::INET; my $host = 'example.com'; my $port = 12345; my $data = 'Hello, server!'; my $socket = IO::Socket::INET->new( PeerAddr => $host, PeerPort => $port, Proto => 'tcp' ) or die "Could not create socket: $!\n"; send($socket, $data, 0) or die "Send error: $!\n"; print "Message sent: $data\n"; close $socket;
In this example, we first specify the hostname and port number of the remote server, as well as the data to be sent. We then create a new TCP socket using the IO::Socket::INET
module, which connects to the remote server using the PeerAddr
and PeerPort
options.
Next, we call the send
function to send the data to the server. The first argument to send
is the socket handle, the second argument is the data to be sent, and the third argument is a set of flags (in this case, 0).
If an error occurs during the send
operation, the die
function is called to print an error message.
Finally, we print a message indicating that the message was sent, and close the socket.
Note that the send
function may not send the entire message at once, depending on the size of the data and the buffer size of the socket. To ensure that the entire message is sent, you may need to call send
multiple times or use a loop.