Perl socket programming

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.