Java nio server http

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

rehmatt/java-http-server

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Css сдвинуть блок вниз

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

This project provides a built-in http server, which can handle GET and HEAD requests to a user specified file system directory under the API /root/*. Besides that the http server provides a simple Wall application to post comments and display them. Therefore extra endpoints were implemented, which uses a MongoDB as database.

The implementation is done with Java 11 and the project uses maven to build the artifacts.

The main method is located in the class ServerApplication. It allows to pass an additional command line argument to specify a different root directory than the default one «./».

All other used classes are implemented as Singleton and will be initialized before starting the http server and after the application.properties were read.

The application.properties can be overridden by specifying the exact same VM args

  • server.host=localhost
  • server.port=8080
  • mongodb.host=localhost
  • mongodb.port=27017
  • mongodb.database=wallApp

The http server is implemented with the package java.nio.channels, which provides a non-blocking server solution. The server is started on localhost:8080 by default and listens to incoming requests. After the request is accepted the requests is read. The request is handled within two specific controller classes. The response is written back to the client socket channel.

The FileController class handles requests to the local file system and serves the static content for the Wall-Application. Therefore the java.nio.file.* package is used intensively.

For creating the JSON string for listing all files and subdirectory of a requested directory the third party library org.json is used.

To handle GET and POST requests from the Wall-Application the CommentController uses the CommentCollection class.

The abstract HttpController provides methods for creating responses and is used by both mentioned controller classes as parent class.

The enum HttpStatus provide some Http status codes and their responses.

Here the connection to the MongoDB is configured and established.

The CommentCollection provides two methods. One for persisting Comments to the MongoDB and one for retrieving the saved comments.

The frontend is implemented with an Angular 8 application and is served as static content from inside the Java application.

  • GET /root/**
    • returns the files content, if the url denotes a file
    • returns a json string containing all files and subdirectories, if the url denotes a directory
    • returns the same response than the GET request, but without the content (file / json string)
    • GET /*
      • returns the static content to display the Wall-Application (e.g. /index.html)
      • returns all saved comments in the local MongoDB
      • stores the passed json object into the local MongoDB

      The third party library logback is used for logging.

      There are three different ways to use the application.

      1. Use an IDE e.g. IntelliJ
      2. Use the executable Jar under the folder executable
      3. Use the provided Dockerfile to build a Docker image
      • IDE (Eclipse or IntelliJ)
      • Java 11
      • Maven
      • nodeJS
      • npm
      • MongoDB running on localhost:27017

      Steps to run the application

      • Clone the repository
      • Execute a «mvn clean install»
      • Run the application (main method is in de.christensen.httpserver.ServerApplication)
      • To specify a different directory use the program arguments to pass in the desired path

      Use the executable Jar under the folder executable

      Steps to run the application

      • Download the http-server.jar
      • Run a terminal window
      • Run the application with «java -jar http-server.jar»
      • To specify a different directory use the program arguments to pass in the desired path
        • E.g. java -jar http-server.jar /path/to/directory

        Use the provided Dockerfile to build a Docker image

        • IDE (Eclipse or IntelliJ)
        • Java 11
        • Maven
        • nodeJS
        • npm
        • MongoDB running on localhost:27017
        • docker

        Steps to run the application

        • Clone the repository
        • Execute «mvn clean install»
        • Execute «docker build -t http-server:1.0.0-SNAPSHOT .»
        • Execute «docker run -p 8080:8080 -e «JAVA_OPTS=-Dmongodb.host=host.docker.internal» http-server»
        • To specify a different directory add JAVA_ARGS=/path/to/directory to docker run
          • E.g. «docker run -p 8080:8080 -e «JAVA_OPTS=-Dmongodb.host=host.docker.internal» -e «JAVA_ARGS=/path/to/directory» http-server»
          • Important: Path has to be inside the docker container unless you mount a host directory during start up with «-v»

          Источник

          Saved searches

          Use saved searches to filter your results more quickly

          You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

          A demo HTTP server built with Java NIO & NIO.2

          puzpuzpuz/http-nio-server

          This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

          Name already in use

          A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

          Sign In Required

          Please sign in to use Codespaces.

          Launching GitHub Desktop

          If nothing happens, download GitHub Desktop and try again.

          Launching GitHub Desktop

          If nothing happens, download GitHub Desktop and try again.

          Launching Xcode

          If nothing happens, download Xcode and try again.

          Launching Visual Studio Code

          Your codespace will open once ready.

          There was a problem preparing your codespace, please try again.

          Latest commit

          Git stats

          Files

          Failed to load latest commit information.

          README.md

          Java NIO simple HTTP server

          A very simple HTTP server that is able to receive GET requests and serve local files. Only HTTP/1.1 is supported.

          This project is an educational project.

          Built for Java 7+ without any external dependencies. Works in a non-blocking fashion and uses Java NIO and NIO.2 (combines reactor and proactor patterns).

          The built .jar file will be located under build/libs/ .

          To start the server with default configuration run:

          java -jar http-nio-server-1.0.0.jar 

          You also can override default configuration by specifying the path as a command line argument:

          java -jar http-nio-server-1.0.0.jar "/home/settings.properties" 

          By default tries to read configuration from settings.properties file located in the folder where server executable was run. Falls back to default configuration if the file was not found.

          Configuration file must have properties format and must have the following settings:

          • port (default: 8080) — server port
          • www_root (default: ) — path to the folder containing files that the server will be serving; empty or missing value means the folder where server executable was run
          • session_timeout_secs (default: 30) — maximum time in seconds that any connection will be served; connection will be closed when the timeout is reached
          • max_connections (default: 10000) — maximum number of simultaneous connections that will be served

          Licensed under MIT License.

          Источник

          One of the most frequency used protocol in the whole Internet *

          * In OSI model, layer 7 Every time you visit a website your web browser uses the HTTP protocol to communicate with web server and fetch the page’s content. Also, when you are implementing backend app and you have to communicate with other backend app — 80% (or more) of cases you will use the HTTP. Long story short — when you want to be a good software developer, you have to know how the HTTP protocol works. And wiring the HTTP server is pretty good way to understood, I think.

          What a web browser sends to the web server?

          Alt Text

          Good question. Of course, you can use «developer tools», let’s do it. Hmm. but what now? What exactly it means? We can see some URL, some method, some status, version (huh?), headers, and other stuff. Useful? Yes, but only to analyze the web app, when something is wrong. We still don’t know how HTTP works.

          Wireshark, my old friend

          Alt Text

          The source of truth. Wireshark is application to analyze network traffic. You can use it to see each packet that is sent by your (or to your) PC. But to be honest — if you know how to use Wireshark — you probably know how HTTP and TCP works. It’s pretty advanced program.

          You are right — the specification

          Every good (I mean — used by more that 5 peoples) protocols should have specification. In this case it’s called RFC. But don’t lie — you will never read this, it’s too long — https://tools.ietf.org/html/rfc2616 .

          Just run the server and test

          Joke? No. Probably you have installed on your PC very powerful tool called netcat, it’s pretty advanced tool.
          One of the netcat features is TCP server. You can run the netcat to listen on specific port and print every thing what it gets. Netcat is a command line app.

          Netcat (nc), please, listen (-l) on port 8080 (-p 8080) and print everything (-v). Now open web browser and enter http://localhost:8080/ . Your browser will send the HTTP request to the server runned by netcat. Of course nc will print the whole request and ignore it, browser will wait for the response (will timeout soon). To kill nc press ctrl+c . So, finally, we have an HTTP request!

          GET / HTTP/1.1 Host: localhost:8080 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:74.0) Gecko/20100101 Firefox/74.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Cookie: JSESSIONID=D3AF43EBFC0C9D92AD9C37823C4BB299 Upgrade-Insecure-Requests: 1 

          HTTP request

          It may be a little confusing. Maybe nc parses the request before printing? HTTP protocol should be complicated, where is the sequence of 0 and 1? There aren’t any. HTTP is really very simple text protocol. There is only one, little trap (I will explain it at the end of this section). We can split the request to the 4 main parts:

          This is the main request. GET — this is the HTTP method. Probably you know there are a lot of methods.
          GET means give me / — resource. / means default one.
          When you will open localhost:8080/my_gf_nudes.html , the resource will be /my_gf_nudes.html HTTP/1.1 — HTTP version. There are few versions, 1.1 is commonly used.

          Host. One server can host many domains, using this field, the browser says which domain it wants exactly

          User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:74.0) Gecko/20100101 Firefox/74.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: keep-alive Cookie: JSESSIONID=D3AF43EBFC0C9D92AD9C37823C4BB299 Upgrade-Insecure-Requests: 1 

          Surprise — empty line. It means: end of the request. In general — empty line in HTTP means end of section.

          The trap

          Response

          Ok. We have a request. How does response look like? Send a request to any server and see, there is nothing simpler.
          On your laptop you can find another very useful tool — telnet . Using telenet you can open TCP connection, write something to server and print the response.
          Try to do it yourself. Run telnet google.com 80 (80 is the default HTTP port) and type request manually (you know how it should look like). To close connection press ctrl+] than type quit . OK. We have a response.

          HTTP/1.1 301 Moved Permanently 

          HTTP/1.1 — version
          301 — status code. I believe you are familiar with that
          Moved Permanently — human-readable status code

          Location: http://www.google.com/ Content-Type: text/html; charset=UTF-8 Date: Wed, 25 Mar 2020 18:53:12 GMT Expires: Fri, 24 Apr 2020 18:53:12 GMT Cache-Control: public, max-age=2592000 Server: gws Content-Length: 219 X-XSS-Protection: 0 X-Frame-Options: SAMEORIGIN 

          Источник

Оцените статью