GET / HTTP/1.1 hello2hallo1What's happening is that when you do select(NEW_HANDLE), then all further print statements (that don't have file handles) will print to the socket NEW_HANDLE, so of course they won't show up on the standard output of the server process. The first browswer will wait (a long time) for the socket to close before it prints anything. If you open up a second browser window, then accept() returns a second time and the old NEW_HANDLE will be closed and the first browser will show its output.
Now, on more general terms, I hope you're doing this only to learn about Perl and/or sockets and/or HTTP at a very low level. If you are just trying to write a server, there are modules for that which handle things for you.
In any case, you should always enable warnings, use strict; and check the return codes of all your socket calls. Here is a sort of minimal HTTP server which may give you an idea of what's going on:
Even if you are interested in working at a very low level, it's still handier to use IO::Socket rather than the naked function calls. E.g. here's the same as the above program:#!perl -w use Socket; use strict; $| = 1; my $queuelength=1; socket(HANDLE, PF_INET, SOCK_STREAM, getprotobyname('tcp')) or die "socket call failed: $!\n"; my $addr = sockaddr_in(80, INADDR_ANY) or die "sockaddr_in: $!\n"; bind(HANDLE, $addr) or die "bind: $!\n"; listen(HANDLE,$queuelength); while(1) { print "hallo1\n"; accept(NEW_HANDLE, HANDLE); my $line; while (defined ($line = <NEW_HANDLE>) && $line ne "\r\n") { print $line; } print NEW_HANDLE "HTTP/1.0 200 OK\r\n"; print NEW_HANDLE "Content-type: text/plain\r\n\r\n"; print NEW_HANDLE "Howdy!\r\n"; close(NEW_HANDLE); print "hello2\n"; }
#!perl -w use IO::Socket; use strict; $| = 1; my $queuelength=1; my $listensock = IO::Socket::INET->new( Proto => 'tcp', LocalPort => 80, Listen => $queuelength, ReuseAddr => 1, ) or die "new listen socket: $!\n"; while(my $newsocket = $listensock->accept) { my $line; print "hello1\n"; while (defined ($line = <$newsocket>) && $line ne "\r\n") { print $line; } print $newsocket "HTTP/1.0 200 OK\r\n"; print $newsocket "Content-type: text/plain\r\n\r\n"; print $newsocket "Howdy!\r\n"; close($newsocket); print "hello2\n"; }
In reply to Re: Perl socket server problem
by Thelonius
in thread Perl socket server problem
by pego
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |