1.0
[HTML] https://delors.github.io/ds-http-and-sockets-java/folien.en.rst.html
[PDF] https://delors.github.io/ds-http-and-sockets-java/folien.en.rst.html.pdf
The network layer (Internet layer)
handles the routing
realizes end-to-end communication
transmits packets
is realized in the Internet through IP
solves the following problems:
Sender and receiver receive network-wide unique identifiers (⇒ IP addresses)
the packets are forwarded by special devices (⇒ routers)
Transmission Control Protocol (TCP), RFC 793
connection-orientated communication
also the concept of ports
Establishing a connection between two processes (triple handshake, full-duplex communication)
Ordered communication
reliable communication
Flow control
high overhead ⇒ rather slow
only unicasts
User Datagram Protocol (UDP), RFC 768
connectionless communication
unreliable (⇒ no error control)
unordered (⇒ arbitrary order)
little overhead (⇒ fast)
Size of the user data is 65507 bytes
Apps with predominantly short messages (e.g. NTP, RPC, NIS)
Apps with high throughput that tolerate some errors (e.g. multimedia)
Multicasts and broadcasts
In practice datagrams (i. e. packages sent using UDP) are usually much smaller than 65507 bytes.
RFC 7230 – 7235: HTTP/1.1 (updated in 2014; orig. 1999 RFC 2626)
RFC 7540: HTTP/2 (standardized since May 2015)
Properties:
Client / server (browser / web server)
based on TCP, usually port 80
Server (mostly) stateless
since HTTP/1.1 also persistent connections and pipelining
Secure transmission (encryption) possible using Secure Socket Layer (SSL) or Transport Layer Security (TLS)
HTTP-Kommandos
("Verbs")
HEAD
GET
POST
PUT
PATCH
DELETE
OPTIONS
TRACE
CONNECT
...
Structure of document identifiers Uniform Resource Locator (URL)
scheme://host[:port][abs_path[?query][#anchor]]
Protocol (case-insensitive) (z. B. http, https oder ftp)
DNS-Name (or IP-address) of the server (case-insensitive)
(optional) if empty, 80 in case of http and 443 in case of https
(optional) path-expression relative to the server-root (case-sensitive)
(optional) direct parameter transfer (case-sensitive) (?from=…&to=…)
(optional) jump label within the document
Uniform Resource Identifier (URI) are a generalization URLs.
defined in RFC 1630 in 1994
either a URL (location) or a URN (name) (e. g. urn:isbn:1234567890)
examples of URIs that are not URLs are XML Namespace Iidentifiers
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">...</svg>
Quite frequently URIs take the shape of URLs and hence are often referred to as URLs thought they do not primarily identify locations but rather names.
Used to request HTML data from the server (request method).
Minimal request:
1GET <Path> HTTP/1.1
2Host: <Hostname>
3Connection: close
4<Leerzeile (CRLF)>
Clients can also send additional information about the request and itself.
Servers send the status of the request as well as information about itself and, if applicable, the requested HTML file.
Error messages may also be packaged by the server as HTML data and sent as a response.
Example request
1GET /web/web.php HTTP/1.1
2Host: archive.org
3**CRLF**
Example response
1HTTP/1.1 200 OK
2Server: nginx/1.25.1
3Date: Thu, 22 Feb 2024 19:47:11 GMT
4Content-Type: text/html; charset=UTF-8
5Transfer-Encoding: chunked
6Connection: close
7**CRLF**
8<!DOCTYPE html>
9…
10</html>**CRLF**
Sockets are communication endpoints.
Sockets are addressed via the IP address (InetAddress object) and an internal port number (int value).
Sockets exist for TCP and also for UDP, but with different properties:
connection-orientated communication via streams
connectionless communication via datagrams
Receiving data is always blocking, i. e. the receiving thread or process waits if no data is available.
The server process waits at the known server port.
The client process creates a private socket.
The socket establishes a connection to the server process - if the server accepts the connection.
Communication is stream-orientated: An input stream and an output stream are set up for both parties, via which data can now be exchanged.
When all data has been exchanged, both parties generally close the connection.
1import java.net.*;
2import java.io.*;
34
public class LowPortScanner {
5public static void main(String [] args) {
6String host = "localhost";
7if (args.length > 0) { host = args [0]; }
8for (int i = 1; i < 1024; i++) {
9try {
10Socket s = new Socket(host, i);
11System.out.println("There is a server on port "+ i + "at "+host);
12s.close();
13} catch (UnknownHostException e) {
14System.err.println(e);
15break ;
16}
17catch (IOException e) {/* probably no server waiting at this port */ }
18} } }
Once the connection has been established, data can be exchanged between the client and server using the Socket-InputStream and Socket-OutputStream.
The best way to do this is to pass the raw data through suitable filter streams in order to achieve the highest possible semantic level.
Examples: PrintWriter
, BufferedReader
, BufferedInputStream
, BufferedOutputStream
Network communication can then be conveniently carried out via well-known and convenient input and output routines (e.g. readLine
or println
).
Filter streams are also used to access other devices and files.
By using the decorater pattern, the filter streams can be nested as required and used in a variety of ways. This makes application programming easier and allows, for example, the simple conversion of character strings, data compression, encryption, etc.
1import java.net.*; import java.io.*;
23
public class EchoClient {
4public static void main(String[] args) throws IOException {
5BufferedReader userIn = new BufferedReader(new InputStreamReader(System.in));
6while (true) {
7String theLine = userIn.readLine();
8if (theLine.equals(".")) break;
9try (Socket s = new Socket("localhost"/*hostname*/, 7/*serverPort*/)) {
10BufferedReader networkIn =
11new BufferedReader(new InputStreamReader(s.getInputStream()));
12PrintWriter networkOut = new PrintWriter(s.getOutputStream());
13networkOut.println(theLine);
14networkOut.flush();
15System.out.println(networkIn.readLine());
16} } } }
1import java.net.*; import java.io.*;
23
public class EchoServer {
4public static void main(String[] args) {
5BufferedReader in = null;
6try {
7ServerSocket server = new ServerSocket(7 /*DEFAULT PORT*/);
8while (true) {
9try (Socket con = server.accept()) {
10in = new BufferedReader(new InputStreamReader(con.getInputStream()));
11PrintWriter out = new PrintWriter(con.getOutputStream());
12out.println(in.readLine()); out.flush() ;
13} catch (IOException e) { System.err.println(e); }
14}
15} catch (IOException e) { System.err.println(e); }
16} }
At the client side
create DatagramSocket
create DatagramPacket
send DatagramPacket
wait for response and process it, if needed
At the server side
create DatagramSocket
with a fixed port
stard endless loop
prepare DatagramPacket
receive DatagramPacket
process DatagramPacket
create and send response if needed
1import java.net.*; import java.io.*;
23
public class UDPEchoServer {
4public final static int DEFAULT_PORT = 7; // privileged port
5public static void main(String[] args) {
6try (DatagramSocket server = new DatagramSocket(DEFAULT_PORT)) {
7while(true) {
8try {
9byte[] buffer = new byte[65507]; // room for incoming message
10DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
11server.receive(dp) ;
12String data = new String(dp.getData(),0,dp.getLength());
13DatagramPacket dp2 =
14new DatagramPacket(data.getBytes(),
15data.getBytes().length, dp.getAddress(), dp.getPort());
16server.send(dp2) ;
17} catch (IOException e) {System.err.println(e);}
18} } } }
A simple HTTP-Client
Write an HTTP client that contacts the server www.michael-eichberg.de, requests the file /index.html and displays the server response on the screen.
Use HTTP/1.1 and a structure similar to the echo client presented in the lecture.
Send the GET command, the host line and an empty line to the server as strings.
Modify your client so that a URL is accepted as a command line parameter.
Use the (existing) class URL to decompose the specified URL.
Modify your program so that the response from the server is saved in a local file. Load the file into a browser for display.
Use the class FileOutputStream
or FileWriter
to save the file.
Can your programme also save image files (e.g. ‘/exercises/star.jpg’) correctly?
Log Aggregation
Write a UDP-based Java program with which log messages can be displayed centrally on a server. The program should consist of several clients and a server. Each client reads an input line from the keyboard in the form of a string, which is then immediately sent to the server. The server waits on port 4999 and receives the messages from any client, which it then outputs immediately.