This section provides a tutorial example on how to write a Perl program using socket interface to send a request and receive a response.
Since most Web services are based on the TCP socket communication,
it is very important to have a socket level testing program ready to troubleshoot
your Web service applications.
So I wrote this simple socket program, SocketRequestResponse.pl, that can be used
to send a request message and receive the response message to a remote TCP based server.
#- SocketRequestResponse.pl
#- Copyright (c) 2009 by Dr. Herong Yang, herongyang.com
#- All rights reserved
#
use Socket;
($host, $port, $in, $out) = @ARGV;
#- Reading the request
open(IN, "< $in");
read(IN, $req, (-s $in));
close(IN);
#- Connecting
socket(SOCK,PF_INET,SOCK_STREAM,getprotobyname('tcp'));
connect(SOCK, sockaddr_in($port, inet_aton($host)));
select(SOCK); $| = 1; select(STDOUT);
#- Sending the request
print SOCK $req;
#- Receiving the response
open(OUT, "> $out");
while ($line=<SOCK>) {
print OUT $line;
}
close(OUT);
#- Closing connection
close(SOCK);
exit;
To try my socket testing program, I prepared this request message in a file, http_get.req,
that can be used to send to any Web server:
GET / HTTP/1.0
Note that my request has 2 new line (\n) characters at the end.
The first \n terminates the GET command. The second \n terminates
the HTTP request header section.
Let's try it with www.yahoo.com first:
\herong>SocketRequestResponse.pl www.yahoo.com 80 http_get.req
http_get.res
\herong>type http_get.res
HTTP/1.1 302 Found
Date: ... 2009
Location: http://m.www.yahoo.com/
Cache-Control: private
Connection: close
Content-Type: text/html; charset=utf-8
<html><body>The document has moved
<a href='http://www.yahoo.com/'>here</a>.</body></html>
<!-- f80.www.re1.yahoo.com uncompressed Fri ... -->
My socket testing program works! But yahoo.com seems to be not happy
about my simple HTTP request. It expects a higher version of HTTP protocol,
HTTP 1.1.