A socket is a procedure which helps to establish a virtual connection between different processes over a network.
A computer receives and sends information by the various applications running on it. This information is routed to the system by a unique IP address assigned to it. The data send during communication is in a "Protocols" format. These Protocols are the rules which are accepted by all communication partners. There are many protocols format with different objectives in socket communication. The most commonly used protocol is TCP/IP protocol.
For a server-client program, we need to create two Perl scripts. One for server and other for client. These two consoles will communicate through each other. You can enter data on client side which will be displayed on server side console.
The following steps are followed to create a socket server.
The following steps are followed to create a client socket.
In this program we have displayed client side data Hello World! on server side console.
Server side script server.pl
#!/usr/bin/perl -w use IO::Socket; use strict; use warnings; my $socket = new IO::Socket::INET ( LocalHost => 'localhost', LocalPort => '1234', Proto => 'tcp', Listen => 1, Reuse => 1, ); die "Could not create socket: $!n" unless $socket; print "Waiting for the client to send data\n"; my $new_socket = $socket->accept(); while(<$new_socket>) { print $_; } close($socket);
Client side script client.pl
use strict; use warnings; use IO::Socket; my $socket = new IO::Socket::INET ( PeerAddr => 'localhost', PeerPort => '1234', Proto => 'tcp', ); die "Could not create socket: $!n" unless $socket; print $socket "Hello World!!\n"; close($socket);
In this client-server program, we'll take input from the users on client console. This input will be displayed on the server's console through client-server communication.
Here the server side scripting will remain same as the earlier one.
Server side script server.pl
#!/usr/bin/perl -w use IO::Socket; use strict; use warnings; my $socket = new IO::Socket::INET ( LocalHost => 'localhost', LocalPort => '1234', Proto => 'tcp', Listen => 1, Reuse => 1, ); die "Could not create socket: $!n" unless $socket; print "Waiting for the client to send data\n"; my $new_socket = $socket->accept(); while(<$new_socket>) { print $_; } close($socket);
Client side script client.pl
use strict; use warnings; use IO::Socket; my $socket = new IO::Socket::INET ( PeerAddr => 'localhost', PeerPort => '1234', Proto => 'tcp', ); die "Could not create socket: $!n" unless $socket; print "Enter the data:\n"; my $data = <STDIN>; chomp $data; print $socket "This is the data entered by user '$data'\n"; close($socket);