I am attempting to write a very simple HTTP server with Perl to serve up a single html file. Almost every time I go to the site, however, I get a "connection reset" error (it does however work something like 5% of the time). I have read this post, but I can't make anything of it.
The server I started with can be found here, but I am attempting to modify it to
a) read in a file instead of using hard-coded html and
b) read this file with every new HTTP request so changes can be seen with a refresh.
Here is my code:
#!/usr/bin/env perl
use strict;
use warnings;
use Socket;
my $port = 8080;
my $protocol = getprotobyname( "tcp" );
socket( SOCK, PF_INET, SOCK_STREAM, $protocol ) or die "couldn't open a socket: $!";
## PF_INET to indicate that this socket will connect to the internet domain
## SOCK_STREAM indicates a TCP stream, SOCK_DGRAM would indicate UDP communication
setsockopt( SOCK, SOL_SOCKET, SO_REUSEADDR, 1 ) or die "couldn't set socket options: $!";
## SOL_SOCKET to indicate that we are setting an option on the socket instead of the protocol
## mark the socket reusable
bind( SOCK, sockaddr_in($port, INADDR_ANY) ) or die "couldn't bind socket to port $port: $!";
## bind our socket to $port, allowing any IP to connect
listen( SOCK, SOMAXCONN ) or die "couldn't listen to port $port: $!";
## start listening for incoming connections
while( accept(CLIENT, SOCK) ){
open(FILE, "<", "index.html") or die "couldn't open "index.html": $!";
while(<FILE>) {
print CLIENT $_;
};
close FILE;
close CLIENT;
}
Any help is appreciated, thanks.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…