1

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.

Community
  • 1
  • 1
  • You have clearly made too many changes before testing. Had you tested even the *original* Perl code in the example you would see that it has the same problem – Borodin Jul 20 '14 at 17:47
  • In MetaCPAN you can find some HTTP servers and every one doing things correctly. You're sure than need reinvent the wheel? (if yes, check some sources, how to do it). – clt60 Jul 20 '14 at 20:35

1 Answers1

0

You don't read the HTTP request from the client, i.e. you close the connection while there are still data to read. This will probably cause the RST.

Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172
  • How would I go about fixing this issue? My journey into the world of Perl started last night, so pardon the inane questions. I can't seem to find much on Google either... If I'm going about this wrong, I'd also appreciate a pointer to a better tutorial, but no obligations. – user3140645 Jul 20 '14 at 17:35
  • 1
    This has not much to do with Perl, but you have to understand how HTTP works. Since you are eager to implement your own server (instead of using existing servers like HTTP::Daemon) you should better read and understand the specification for HTTP, i.e. RFC2616. – Steffen Ullrich Jul 20 '14 at 18:24