A Simple Http Server with Java/Socket?

后端 未结 5 1217
耶瑟儿~
耶瑟儿~ 2020-11-29 03:11

I am currently creating a small HTTP server that returns a static page

Hello!

... I tried with sockets with Java:

  public sta         


        
5条回答
  •  离开以前
    2020-11-29 03:39

    Just a reminder: this is not an HTTP server, as the title would suggest. It is a socket that writes out one specific hard-coded HTTP response (assuming it is fixed according to suggestions in the other answers). Even if you changed the returned content and content length header dynamically, that's still not enough to be compliant with the HTTP protocol.

    As I learned the hard way while writing JLHTTP, There's a lot more to HTTP than that. It's not that it's very complicated, but just that there are a lot of additional details and requirements to be properly handled. You can read the RFCs (the core protocol is defined in RFC 7230, or the older RFC 2616) to learn more about what this entails.

    I can also offer up the JLHTTP source code as a reference for a well-documented minimal compliant implementation of an HTTP server - it is one file, currently ~3K lines of which almost half are documentation. Its goal is to be tiny, but compliant. I think looking at the code can be useful for anyone wanting to learn what an HTTP server has to do. As I said - not very complicated, but with a lot of little details.

    Actually, to be exact, JLHTTP is not as minimal as possible - it does include a few useful extra features, like handling multipart form data for file uploads or supporting HTTPS, which are not required by the HTTP protocol itself. But you can easily rip those parts out (or just skip them) and arrive at a truly minimal Java HTTP server implementation.

提交回复
热议问题