Chandan Rajpurohit

An Artist With Technical Skills

What is SOCKET?

Socket is a mechanisms that creates virtual connection between different processes. Established connection is duplex in nature. This was scaled over OS for communication between systems across geographical location. Network communication between systems happens only because of Socket.

Let’s understand Socket programming using SERVER-CLIENT model.

Server Side Socket Calls :

For creating a server, we first create a socket. Then bind socket to a port. We listen to socket and accept client connections.

socket(socket, domain, type, protocol) #creating a socket 

bind(socket, address) #binding socket to port

listen(socket, queuesize) #listening to socket

accept(socket_conn, socket) #accepting calls 

Client Side Socket calls

Create a socket and connect call to server.

socket(socket, domain, type, protocol)   #create a socket

connect(socket, address) #connect to server

Now we create an example of Socket (server-client) communication.

#SERVER-SIDE

use strict;
use socket;

my $port = "";   #set port or use default
my $protcol = "";  #set protocol (tcp/udp)
my $server = "";  #set server name or use localhost

socket (socket,pf_inet,sock_stream,$protcol) or die "unable to open socket \n";

setsockopt(socket,connection_type,useraddr,1) or die "unable to set socket option to useraddr \n";

bind(socket,pack_sockaddr_in($port,inet_aton($server))) or die "unable to bind port \n";

listen(socket,5);
print "STARTED xD";

my $client;

while($client=accept(conn,socket)){
print conn= "Hello There";

while (my $recv = <$conn>){
print $recv;
}

# to close connection 
close conn;
}



#Client-side
use strict;
use socket;

my $port = "";   #set port or use default
my $host = "";  #set host or use localhost
my $server = "";  #set server name or use localhost
my $protcol = "";  #set protocol (tcp/udp)

socket (socket,pf_inet,sock_stream,$protcol) or die "unable to open socket \n";

connect(socket,pack_sockaddr_in($port,inet_aton($server))) or die "unablen to connect to $port \n";

my $recv;

while($recv=<socket>){
print $recv;

print $socket "GENERAL KENOBI!!!!"
}

close socket or die "THIS IS THE WAY";

O/P:
Hello There
GENERAL KENOBI

Keep Learning! ๐Ÿ™‚
May The Force Be With You


Leave a Reply

%d bloggers like this: