- How to Make a Server in Java in 5 Easy Steps
- Before You Begin
- Getting Started with Java 18 (and above)
- A Quick Overview of Java 18
- Understanding the Java 18 Features for Web Development
- Considering jwebserver Limitations
- How to Make a Server in Java
- Step 1: Install Java 18
- Первое знакомство с протоколом HTTP через написание простейшего Web сервера на Java
How to Make a Server in Java in 5 Easy Steps
Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.
Everyone likes the idea of reducing their workload when possible, yet the need to perform basic functionality arises almost constantly. Often, developers end up doing a lot of work for what seems like little return, especially when it comes to basic web design. You don’t need a full-fledged web server to perform quick checks for things like connectivity or to ensure basic functionality. This is where Java 18’s newfound web functionality comes into play. Java 18 sets up and configures a basic Java web server you can use for simple tasks. It only takes a matter of minutes, rather than hours, and it’s a pretty straightforward process. This guide demonstrates how to work with Java 18’s web functionality to create a server in Java. It also covers how to use the jwebserver command line tool.
Before You Begin
- If you have not already done so, create a Linode account and Compute Instance. See our Getting Started with Linode and Creating a Compute Instance guides.
- Follow our Setting Up and Securing a Compute Instance guide to update your system. You may also wish to set the timezone, configure your hostname, create a limited user account, and harden SSH access.
This guide is written for a non-root user. Commands that require elevated privileges are prefixed with sudo . If you’re not familiar with the sudo command, see the Users and Groups guide.
Getting Started with Java 18 (and above)
Java 18 and above have much to offer in the way of web functionality. The following sections provide an overview of Java 18 web functionality used for Java web hosting at the developer level. A detailed look at the jwebserver command line tool is also provided.
A Quick Overview of Java 18
Java 18 has new functionality that makes it easier to create, test, debug, and simulate a Java API server, among other things. Java 18 also includes features like a vector API, previews pattern matching for switch expressions, and UTF-8 as the default character set. There are many advances in server-side programming when working with Java 18. In fact, there are nine major new features that you need to know about as a developer to create a better server:
- It deprecates Finalizer for removal in a future release to reduce security, performance, reliability, and maintainability issues.
- It defines Stateful Packet Inspection (SPI) for Internet address resolution to better enable Project Loom, concurrency, new programming models, network protocols, customization, and testing.
- It provides a preview of pattern matching for switch expressions and statements (something that was originally previewed in Java 17, but enhanced in this release).
- It reimplements lang.reflect.Method , Constructor , and Field on top of java.lang.invoke method handles.
- It offers an out-of-the-box static Java HTTP file server with easy setup and minimal functionality.
- It formalizes a second iteration of the foreign function and memory API, which allows Java program interoperation with code and data outside the Java runtime.
- It creates a method to express vector computations that compile at runtime using the vector API originally introduced in Java 16 and updated in Java 17.
- It uses UTF-8 (the web’s standard charset) to make web server data encoding easier and reduce the potential for applications behaving incorrectly when they use a different default charset.
- It introduces the @snippet tag for JavaDoc’s Standard Doclet to simplify the inclusion of sample code in the API documentation.
Understanding the Java 18 Features for Web Development
jwebserver reproduces the developer-grade web servers provided in languages like Python, Ruby, PHP, and Erlang. This is a basic web server, and the documentation tells you a lot about its limitations. On the upside, not stated in the documentation is that the simplicity of the web server doesn’t affect the operating systems or its features. It’s entirely possible to perform various setups and configurations that normally require a lot of time using the operating system and third party tools. Think of this server as something to use in a simulation, for demonstration purposes, or for tasks such as simulating an API. For example, a development team can use this web server to share files or create documentation.
Considering jwebserver Limitations
The web server included with Java 18 provides a simple activation server that developers can use to serve static files. These files must all appear in a single directory, but this isn’t a problem for the web server’s intended purpose. As described in JEP408, the purpose is to develop a minimal web server that a developer can interact with using an API that allows customization. The jwebserver doesn’t replace commercial-grade web servers, such as Jetty, Netty, and Grizzly. Nor production-grade web servers, such as Apache Tomcat, Apache httpd, and NGINX. It does provide a functional option that allows developers to avoid installing and configuring full-fledged web servers just so they can get to work. The web server itself doesn’t provide security features, such as authentication, access control, or encryption. The idea here is to save time developing a full-fledged server. This allows the developer to perform testing, debugging, and development without a lot of effort.
How to Make a Server in Java
These steps walk you through the process of installing Java 18, accessing the jwebserver command line utility, and performing specific tasks using jwebserver and its associated components. It extends these basic principles to perform tasks like providing Java web hosting and performing server-side programming in Java, with less fuss than ever.
Step 1: Install Java 18
These steps show how to install the Oracle Java Development Kit (JDK) 18 on an Ubuntu 22.04 LTS system. They also work with other versions of Linux.
Первое знакомство с протоколом HTTP через написание простейшего Web сервера на Java
Думаю что не будет преувеличением утверждать, что знание и понимание сути протокола HTTP необходимо любому, кто решил сколь-нибудь серьезно заняться любым из направлений современной Web разработки. Мой личный опыт говорит о том, что понимание это приходит не сразу. Стыдно сказать, что были времена, когда слова GET и POST были для меня сродни магическим заклинаниям, а о существовании PUT, PATCH и DELETE я даже не подозревал.
Несколько месяцев назад помимо собственно разработки я занялся также преподаванием, и возник вопрос о том, как проще и понятнее рассказать о сути протокола HTTP будущим Java разработчикам. После нескольких дней возни и ряда неудачных попыток сделать презентацию возникла идея, а почему бы не написать простейший HTTP сервер на Java, потому как ни что так хорошо не объясняет суть протокола, как его простейшая, но работающая реализация.
Как оказалось сделать это совсем не сложно. Ниже привожу код, которого будет достаточно для корректного взаимодействия с любым браузером! Все что нам понадобится это ServerSocket и немного стандартного ввода-вывода.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.nio.charset.StandardCharsets; public class HttpServer < public static void main(String[] args) < try (ServerSocket serverSocket = new ServerSocket(8080)) < System.out.println("Server started!"); while (true) < // ожидаем подключения Socket socket = serverSocket.accept(); System.out.println("Client connected!"); // для подключившегося клиента открываем потоки // чтения и записи try (BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8)); PrintWriter output = new PrintWriter(socket.getOutputStream())) < // ждем первой строки запроса while (!input.ready()) ; // считываем и печатаем все что было отправлено клиентом System.out.println(); while (input.ready()) < System.out.println(input.readLine()); >// отправляем ответ output.println("HTTP/1.1 200 OK"); output.println("Content-Type: text/html; charset=utf-8"); output.println(); output.println("Привет всем!
"); output.flush(); // по окончанию выполнения блока try-with-resources потоки, // а вместе с ними и соединение будут закрыты System.out.println("Client disconnected!"); > > > catch (IOException ex) < ex.printStackTrace(); >> >
Пробуем запустить этот код. Стоит отметить, что порт, для которого создается ServerSocket должен быть свободным. Если указанный порт занят, то нужно или его освободить, или использовать другой свободный порт.
После запуска этого кода идем в окно браузера и набираем в адресной строке http://localhost:8080/ . Если все прошло удачно, то в окне браузера мы увидим текст «Привет всем», а в логе сервера текст, подобный приведенному ниже:
Server started! Client connected! GET / HTTP/1.1 Host: localhost:8080 Connection: keep-alive Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding: gzip, deflate, br Accept-Language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,he;q=0.6,de;q=0.5,cs;q=0.4 Cookie: _ga=GA1.1.1849608036.1549463927; portainer.pagination_containers=100; _gid=GA1.1.80775985.1550669456; If-Modified-Since: Sat, 05 Jan 2019 12:10:16 GMT Client disconnected!
Каждый раз, когда мы что-то вводим в адресную строку браузера и нажимаем Enter не происходит ничего иного, как отправка текста, начинающегося словом GET и заканчивающегося переводом строки. После слова GET через пробел следует путь к запрашиваемому документу на сервере. Попробуйте ввести в браузере http://localhost:8080/something и посмотреть, как изменится текст запроса в логе.
В строках запроса, начиная со второй находятся т.н. заголовки при помощи которых осуществляется передача серверу информации о настройках клиента. Каждая строка заголовка имеет формат [имя заголовка] : [значение]; [значение]; . [значение] .
После того, как текст запроса полностью прочитан сервером, мы отправляем ему простейший ответ, структура которого довольно проста и аналогична структуре запроса. В первой строке версия протокола HTTP и код 200 OK, который сообщит браузеру о том, что запрос был успешно обработан (всем куда лучше знаком код 404, не правда ли 😉 ). Далее следует всего один заголовок Content-Type в котором передается информация о формате передаваемого документа (text/html) и его кодировке (charset=utf-8). После заголовка следует перевод строки (обязательное требование протокола HTTP) и собственно текст, который будет отображен в браузере.
На этом все! Разумеется это далеко не все, что нужно знать о протоколе HTTP и принципах разработки Web серверов, но мне бы не хотелось усложнять данный пример, т.к. главная его задача — продемонстрировать, простейшую коммуникацию по протоколу HTTP. В одном из следующих своих материалов постараюсь развить тему изучения протокола HTTP через его реализацию.
UPD. Гораздо более продвинутый пример подобного сервера можно найти в книге How Tomcat Works: A Guide to Developing Your Own Java Servlet Container by Paul Deck, Budi Kurniawan, глава 1 — Simple Web Server.