Simple web server hangs when receiving http request

I'm writing a simple web server,code snippet:

ServerSocket server = new ServerSocket(80); Socket client=server.accept(); InputStream in=client.getInputStream(); OutputStream out=client.getOutputStream(); int val = -1; while ((val = != -1) { System.out.print((char) val); } BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( out)); writer.write("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\nhello world!"); writer.close(); out.close(); in.close();

I run it on my computer,then visit in Firefox. The page hangs and could'nt show "hello world".I think the problem occurs in while ((val = != -1),how to solve it?

-------------Problems Reply------------

HTTP (at least the 1.1 version) allows letting the connection open. The request is then ended by an empty line (i.e. "\r\n\r\n"), if it is not a POST or PUT request with contents. After this, the client can send the next request on the same connection.

So you have to read the input at least for scanning for your empty line.

Edit: To clarify this a bit, some quotes from RFC 2616 (which defines HTTP 1.1).

Section 4.1, Message Types:

Request (section 5) and Response (section 6) messages use the generic message format of RFC 822 [9] for transferring entities (the payload of the message). Both types of message consist of a start-line, zero or more header fields (also known as "headers"), an empty line (i.e., a line with nothing preceding the CRLF) indicating the end of the header fields, and possibly a message-body.

generic-message = start-line
*(message-header CRLF)
[ message-body ]
start-line = Request-Line | Status-Line

So, message header and message body are delimited by an empty line (the first one after the start line).

Section 4.3 Message Body:

The message-body (if any) of an HTTP message is used to carry the entity-body associated with the request or response. [...]

The rules for when a message-body is allowed in a message differ for requests and responses.

The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers. A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests. A server SHOULD read and forward a message-body on any request; if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.

So in principle, clients must only send a body when the method allows it, but servers should ignore superfluous message bodies, if they are sent on a method that does not support it. And the presence of a body is indicated by the Content-Length or Transfer-Encoding header fields.

The subsections of section 9 define the individual methods.

  • 9.2 OPTIONS
    • can contain a body, but meaning is not defined
  • 9.3 GET
    • can contain no body
  • 9.4 HEAD
    • can contain no body
  • 9.5 POST
    • should (or must?) contain a body
  • 9.6 PUT
    • should (or must?) contain a body
  • 9.7 DELETE
    • can contain no body
  • 9.8 TRACE
    • can contain no body
  • 9.9 CONNECT
    • (this method is reserved)

Anyway, independently of whether the client sends a body or not, and whether it reuses the connection for the next request or not, it will normally not close the connection before the response is read, since otherwise your server could not resend the response at all. So you simply can't wait on a close when reading the request, but have to somehow know when it ended to send your response.

For your simple hello world server which only handles get requests you can simply say "read until the first empty line".

For a real server (i.e. one that is visible to the outside world), you should at least parse the request, ignore any body, and handle HEAD differently than GET (that is, not sending any body back), and send error responses for unsupported methods.

Category:java Views:1 Time:2011-03-30

Related post

  • The Web Server Could Not Find the Requested Resource 2008-11-13

    I have a .NET 3.5 Web application on VS 2008 SP1 running on Vista Ultimate 32 SP1. I created an Application under the Default Web Site. So the url to the app is "http://localhost/mysite". The application folder is pointing to the solution folder and

  • How do I create a simple Web Server using WCF without the ServiceHost class? 2010-07-01

    I've began to learn WCF and wish to understand its internals by creating a simple Web server using channel stacks directly. I have found a lot of theory in the web but I'd like to see a working sample code of receiving and responding an httprequest t

  • I need a simple web server with a console 2010-11-17

    My problem is I am adding an Ajax client to an existing RPC web service. i have a PHP client that talks to it, a java jibx.POX client that talks to it, a pure java http client that i wrote that talks to it, everything. but when i try to put my jquery

  • Using node.js as a simple web server 2011-05-21

    I want to run a very simple HTTP server. Every GET request to should get index.html served to it but as a regular HTML page (i.e., same experience as when you read normal web pages). Using the code below, I can read the content of index.h

  • Simple Web Server and MVC framework for Java 2009-04-15

    Does anyone know of a simple Web MVC framework and Web Server for Java that is open source? This is intended as a simple web server and framework for students in a tutorial class. It's important these both the web server and MVC framework are simple,

  • Trying to build VERY SIMPLE WEB SERVER in java and it freezes 2011-04-06

    I'm trying to build a VERY simple web server. I got it to work. Right now I use an InputStream and stop at the end of the first line. I figured I could stop when a -1 is returned (since that would be the end of the stream) but it freezes. Why? connec

  • Simple Web Server C# 2011-05-19

    I need some help with this code: using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.IO; namespace HttpEcho { class HttpEchoProgram { static void Main(string[] args) { TcpListener server = new TcpL

  • How can I implement a simple web server using Python without using any libraries? 2012-04-10

    I need to implement a very simple web-server-like app in Python which would perform basic HTTP requests and responses and display very basic output on the web page. I am not too concerned about actually coding it in Python, but I am not sure where to

  • Build a simple web server that I can run as a windows service 2010-06-27

    I'm a web developer so all my experience is with ruby, python, or PHP. However, I'm gonna do a little windows programming. I want to build a light weight web server that can handle incoming requests and pass them on to a COM port. I want to be able t

  • Unable to start debugging on the web server. The web server could not find the requested resource 2010-09-28

    I'm having this error trying to debug my ASP.NET MVC app. I've set the app to "Use Local IIS Web server", and selected ASP.NET as the debugger. Running the site without debugging works just fine, but when I try to debug, I got this error: Unable to s

  • Simple web server with authentication 2013-05-03

    I want to implement a simple web server (like apache), with static content. The server must offer authentication by username and password or by IP address. Source code or any usefull tutorial will be really helpful. Thanks for your answers. ---------

  • Java server hangs on receiving HTTP post request 2011-03-30

    I am trying to implement a simple client-server communication. Here my client is an Android device which uses org.apache.http library to send some data using POST method and a java server handles the request. Client side: public class Client implemen

  • Creating a python web server to recieve XML HTTP Requests 2011-02-04

    I am currently working on a project to create simple file uploader site that will update the user of the progress of an upload. I've been attempting this in pure python (with CGI) on the server side but to get the progress of the file I obviously nee

  • Why does a simple Thin server stop responding at 16500 requests when benchmarking? 2012-02-06

    Possible Duplicate: 'ab' program freezes after lots of requests, why? Here's a simple test server: require 'rubygems' require 'rack' require 'thin' class HelloWorld def call(env) [200, {"Content-Type" => "text/plain"}, "OK"] end end Rack::Handler:

  • Hebrew strings submitted to web server aren't received in Hebrew 2011-09-13

    I submit a sign up form from my app to the web server: EditText email = (EditText)findViewById(; EditText password = (EditText)findViewById(; EditText nickname = (EditText)findViewById(; List<NameValuePair

  • How to set up a simple web server(Windowws XP Pro) 2009-12-14

    As a heads up, I have some experience programming on Windows and other devices, but I have almost zero experience doing web anything, so I'm sure this is simple/easy to find online and I just don't know what I'm doing. I have a computer on my home ne

  • Ruby Rack - mounting a simple web server that reads index.html as default 2010-10-05

    I'm trying to get some information from this tutorial: basically I want to have a file that tell rack to read the current directory so I can access all the files just like a simple a

  • can i restrict mongoose web server to not Accept http request but only from the host application 2010-10-26

    Hi I embedded the mongoose web server in my application it just showing bunch of web pages I opening port on localhost , but its mean I can send request from any ware in the network , this is something I like to prevent Is there any way to tell the w

  • Java Multithreaded Web Server - Not recieving multiple GET requests 2011-02-05

    I have the starts of a very basic multi-hreaded web server, it can recieve all GET requests as long as they come one at a time. However, when multiple GET requests come in at the same time, sometimes they all are recieved, and other times, some are m

Copyright (C), All Rights Reserved.

processed in 0.089 (s). 11 q(s)