Soket is a network socket. It is a combination of IP addresses and port numbers. The socket module is required to use sockets in Perl. It can be used after testing: The following example is used for illustration:
Server:
#! /Usr/bin/perl-W
Use SOCKET;
Use IO: handle;
Socket (sock, af_inet, sock_stream, getprotobyname ("TCP"); # initialize the socket
Setsockopt (sock, sol_socket, so_reuseaddr, 1 );
My $ ADDR = sockaddr_in (3000, inaddr_any );
BIND (sock, $ ADDR); # Bind Address
Listen (sock, somaxconn); # Listen
While (1)
{
Print "wait for a connect \ n ";
While (1 ){
Last if my $ addr1 = accept (S, sock); # receive connections
}
Print "connected \ n ";
S-> autoflush (1); # The content can be output directly without being cached.
While (1 ){
Next unless $ msg_in = <S>; # use the same socket descriptor as the file descriptor, which is more convenient than the socket of C. Of course, you can also use functions such as send and Recv. Note that the received content must end with a line break.
Last if ($ msg_in = ~ /Quit/I | $ msg_in = ~ /Q/I );
Print "$ msg_in ";
Print s "send back: $ msg_in ";
}
}
Close S;
Close sock;
Client:
#! /Usr/bin/perl-W
Use SOCKET;
Use IO: handle;
Socket (sock, af_inet, sock_stream, getprotobyname ("TCP "));
My $ ADDR = sockaddr_in (3000, inet_aton ("localhost "));
Connect (sock, $ ADDR );
Sock-> autoflush (1 );
While (1 ){
Print "Send MSG: \ n ";
$ In = <stdin>; # It already contains the Terminator.
If ($ in = ~ /Quit/I | $ in = ~ /Q/I)
{
Print sock "$ in ";
Print "Bye \ n ";
Exit 1;
}
Else
{
Print sock "$ in ";
$ HH = <sock>;
Print "recieve massage from server: $ HH ";
}
}
Perl socket programming