How to send and receive data from a single socket in perl??
Hello everyone,
What my server want to do is:
1. Connect to one client only and one server only
2. Receive data from the client
3. If something is received then create a child process and in the child process send the data to another server and send the response of that server to the client.
4. In the meantime my server want to receive more data from the same client simultaniously.
So you can say that it is a middleware
This is my code:
whats wrong with it? please help.
#!/usr/bin/perl
use IO::Socket;
$SIG{CHLD} = sub {wait ()};
my $main_sock = new IO::Socket::INET(
LocalHost => '120.50.8.8',
LocalPort => 4000,
Proto => 'tcp',
Listen => SOMAXCONN,
Reuse => 1);
die "Socket could not be created. Reason: $!\n" unless ($main_sock);
my $cbsSocket = new IO::Socket::INET(PeerPort=>5000, PeerHost=>'120.50.8.8', Proto=>'tcp');
die "Socket could not be created. Reason: $!\n" unless ($cbsSocket);
while ($new_sock = $main_sock->accept())
{
while($new_sock->recv($buf,10000))
{
print "SOCKET READY \n";
print "%%".$buf."%%\n";
if($buf eq '')
{
}
else
{
$pid = fork();
die "Cannot fork: $!" unless defined($pid);
if($pid == 0)
{
print "** INSIDE CHILD PROCESS ** \n";
#do some manipulation wiht the data $buf
#sending $buf to another server that will return me buf2
$cbsSocket->send($buf);
$cbsSocket->recv($buf2, 10000);
# Now sending $buf2 to the client from which I received $buf
if($buf2 ne '')
{
print "inside if \n";
if($new_sock->send($buf2))
{
print "*** Sending SUCCESSFUL ***\n";
}
else
{
close($new_sock);
print "***** cannot send ****** \n";
last;
}
}
else
{
print "*** EXCEPTION NO RESPONSE *** \n";
print "*** SENDING EMPTY *** \n\n";
$a = "NO REPLY";
$new_sock->send($a);
}
}
}
#close($new_sock);
kill($pid);
print "** EXIT FROM CHILD PROCESS ** \n";
#$new_sock->autoflush(1);
#$new_sock = $main_sock->accept();
exit 0;
}
print "RETURN TO PARENT \n";
#$new_sock->autoflush(1);
#close($new_sock);
#$new_sock = $main_sock->accept();
}
if(!$new_sock)
{
print "SOCKET DESTROYED \n";
}
#exit(0);
}
#close($new_sock);
}
#close ($main_sock);
|