Java TCP and UDP programming

Java TCP and UDP programming

Link to the course

L. Delafontaine and H. Louis, with the help of GitHub Copilot.

Based on the original course by O. Liechti and J. Ehrensberger.

This work is licensed under the CC BY-SA 4.0 license.

Java TCP and UDP programming

Objectives (1/2)

  • Program your own TCP client/server applications in Java with the Socket API.
  • Process data from TCP streams.
  • Program your own UDP emitter/receiver applications in Java with the Socket API.
  • Process data from UDP datagrams.
Java TCP and UDP programming

Objectives (2/2)

  • Learn the different ways to send a UDP datagram to one or multiple clients.
  • How UDP can be used for service discovery.
  • Make usage of a REPL.

Your applications will be able to communicate over the network!

Java TCP and UDP programming

Part 1/2

In this first part, you will learn the basics of TCP and UDP programming in Java.

Java TCP and UDP programming

Explore the code examples

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

Explore the code examples

Individually, or in pair/group, take 15 minutes to explore and discuss the code examples (part 1/2).

Answer the questions available in the course material:

  • How do the code examples work?
  • What are the main takeaways of the code examples?
  • What are the main differences between the code examples?

If needed, use the theoretical content to help you.

Java TCP and UDP programming

The Socket API

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

The Socket API

  • Java API to create TCP and UDP network applications.
  • Described in the java.net package in the java.base module.
  • Originally developed by Berkeley University for the Unix operating system.
  • Ported to Java and many other languages.
  • Provides classes and methods to create sockets, connect to remote hosts, send and receive data, etc.
Java TCP and UDP programming

TCP

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

TCP

TCP is a transport protocol that is similar to a phone call:

  1. A connection is established between two parties (unicast).
  2. Data sent is guaranteed to arrive in the same order.
  3. Data can be sent again if needed (retransmission).
Java TCP and UDP programming

TCP in the Socket API

  • The Socket API provides two classes to create TCP applications:
  • A TCP socket is a connection endpoint between two parties using a host and a port.
  • A server socket listens for incoming connections on a specific port.
  • A client socket connects to a server socket using the server's host and port.
  • Once connected, data can be exchanged between the two sockets.
Java TCP and UDP programming
Java TCP and UDP programming
Java TCP and UDP programming
Java TCP and UDP programming
Java TCP and UDP programming
Java TCP and UDP programming

Processing data from streams

  • Sockets use data streams to send and receive data, just like files:
    • Get an input stream to read data from a socket.
    • Get an output stream to write data to a socket.
Java TCP and UDP programming

Get the streams from a socket:

// Get input stream
input = socket.getInputStream();

// Get output stream
output = socket.getOutputStream();

Read and write data from/to the streams as text:

// Get input stream as text
input = new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8);

// Get output stream as text
output = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8);
Java TCP and UDP programming

Improve performance with a buffer (with a binary stream):

// Get input stream as binary with buffer
input = new BufferedInputStream(socket.getInputStream());

// Get output stream as binary with buffer
output = new BufferedOutputStream(socket.getOutputStream());

Everything you have learned about Java IOs applies here!

Java TCP and UDP programming

UDP

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

UDP

  • A transport layer protocol just like TCP.
  • Connectionless protocol - does not require to establish a connection before sending data.
  • Unreliable protocol - does not guarantee delivery but is fast.
  • Analogy: sending postcards through the postal service.
Java TCP and UDP programming

UDP datagrams

  • Datagrams are discrete chunks of data (packets) sent over the network.
  • Sent individually and independently, just as postcards.
  • Each datagram is self-contained and has all the information needed for routing and delivery, thanks to its header.
  • The header contains the source's IP, source and destination ports, length, checksum, etc. and a payload (data).
  • Maximum size of a UDP datagram is 65,535 bytes (including header).
Java TCP and UDP programming

Reliability

  • UDP is unreliable (no guarantee of delivery, no guarantee of order).
  • The application must implement its own reliability mechanism.
  • In some cases, reliability is not needed (e.g. streaming).
  • Handling reliability is complex - not covered in this course.
Java TCP and UDP programming

UDP in the Socket API

  • DatagramSocket is used to send and receive datagrams.
  • A datagram is created with the DatagramPacket class.
  • A datagram socket can send and receive datagrams to/from any host and port.
  • A datagram socket can be bound to a specific port to listen for incoming datagrams.
  • A datagram socket can be used to send and receive datagrams without establishing a connection.
Java TCP and UDP programming
Java TCP and UDP programming
Java TCP and UDP programming
Java TCP and UDP programming
Java TCP and UDP programming

Processing data from datagrams

A datagram contains a payload as a byte array.

You can create a datagram with a byte array as payload:

// Create a datagram with a payload and a destination address
byte[] buffer = "Hello, World!".getBytes(StandardCharsets.UTF_8);
DatagramPacket packet = new DatagramPacket(
  buffer,
  buffer.length,
  InetAddress.getByName("localhost"),
  1234
);
Java TCP and UDP programming

You can get the payload of a received datagram as a byte array:

// Create a datagram to receive data
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

// Receive a datagram
socket.receive(packet);

// Get the payload of the datagram
byte[] data = packet.getData();
int length = packet.getLength();
String message = new String(data, 0, length, StandardCharsets.UTF_8);
Java TCP and UDP programming

End of part 1/2 - Questions

Do you have any questions?

Java TCP and UDP programming

Practical content (part 1/2)

Java TCP and UDP programming

What will you do?

  • Learn to use the debugger.
  • TCP & UDP - Execute the code examples.
  • Explore the Java TCP programming template.
  • Explore the Java UDP programming template.
Java TCP and UDP programming

Now it's your turn!

  • Read the course material.
  • Do the practical content.
  • Ask questions if you have any.

➡️ Find the course on GitHub.

Do not hesitate to help each other! There's no need to rush!

Java TCP and UDP programming

Part 2/2

In this second part, you will learn more about UDP and some of its unique features compared to TCP.

Java TCP and UDP programming

Explore the code examples

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

Explore the code examples

Individually, or in pair/group, take 15 minutes to explore and discuss the code examples (part 2/2).

Answer the questions available in the course material:

  • How do the code examples work?
  • What are the main takeaways of the code examples?
  • What are the main differences between the code examples?

If needed, use the theoretical content to help you.

Java TCP and UDP programming

Unicast, broadcast and multicast

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

Unicast, broadcast and multicast

  • Unicast, broadcast and multicast are ways to send data over the network.
  • TCP is unicast only - one sender and one receiver.
  • UDP can be unicast, broadcast or multicast.
Java TCP and UDP programming

Unicast

  • One-to-one communication.
  • One sender and one receiver.
  • To send a datagram, the sender must know:
    • The IP address of the receiver.
    • The port of the receiver.

Think of it as a private conversation between two people.

Java TCP and UDP programming

Broadcast

  • One-to-all communication.
  • One sender and multiple receivers.
  • To send a datagram, the sender must know:
    • The network subnet (e.g. 192.168.255.255).
    • The port.

Think of it as a public announcement.

Java TCP and UDP programming

Multicast

  • One-to-many communication.
  • One sender and some receivers.
  • To send a datagram, the sender must know:
    • The multicast address (between 239.0.0.0 and 239.255.255.255).
    • The port.

Think of it as a group conversation.

Java TCP and UDP programming
  • Just as with broadcast, it can be blocked by routers.
  • Broadcast/multicast are quite guaranteed not to work on the public Internet.
  • Made for the local network.
  • Multicast is a complex topic, not covered in depth in this course.
  • The course material contains some resources.
Java TCP and UDP programming

Messaging patterns

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

Messaging patterns

  • Fire-and-forget:
    • One-way communication.
    • No response.
    • No guarantee of delivery.
  • Request-response:
    • Two-way communication.
    • Response.
    • Guarantee of delivery (manual).
Java TCP and UDP programming

Service discovery protocols

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

Service discovery protocols

  • Discover services on the network.
  • Service discovery protocol patterns:
    • Advertisement (passive).
    • Query (active).
Java TCP and UDP programming
Java TCP and UDP programming
Java TCP and UDP programming

Read-Eval-Print Loop (REPL)

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

Read-Eval-Print Loop (REPL)

A REPL is a concept that allows you to interact with a program by sending commands to it without restarting it.

In networking, it is used to send commands to a server that will read the commands, evaluate them, and send back the result.

All of this is done in a loop until the client or the server decides to close the connection.

Useful to keep a connection open and send multiple commands!

Java TCP and UDP programming

Differences between TCP and UDP

More details for this section in the course material. You can find other resources and alternatives as well.

Java TCP and UDP programming

Summary of differences between TCP and UDP

  • TCP:
    • Connection-oriented.
    • Reliable.
    • Stream protocol.
    • Unicast.
    • Request-response.
    • Used for FTP, HTTP, SMTP, SSH, etc.
Java TCP and UDP programming
  • UDP:
    • Connectionless.
    • Unreliable.
    • Datagram protocol.
    • Unicast, broadcast and multicast.
    • Fire-and-forget, request-response (manual).
    • Service discovery protocols.
    • Used for DNS, streaming, gaming, etc.
Java TCP and UDP programming

Questions

Do you have any questions?

Java TCP and UDP programming

Practical content (part 2/2)

Java TCP and UDP programming

What will you do?

  • TCP & UDP - Execute the remaining code examples.
  • Update the "Guess the number" and "Temperature monitoring" application protocols.
  • TCP - Try to access the TCP server from multiple TCP clients at the same time.
  • UDP - Try to emit from multiple UDP emitters at the same time.
  • Implement and Dockerize the "Guess the number" game (optional).
  • Implement and Dockerize the "Temperature monitoring" application (optional).
Java TCP and UDP programming

Finished? Was it easy? Was it hard?

Can you let us know what was easy and what was difficult for you during this chapter?

This will help us to improve the course and adapt the content to your needs. If we notice some difficulties, we will come back to you to help you.

➡️ GitHub Discussions

You can use reactions to express your opinion on a comment!

Java TCP and UDP programming

Sources (1/2)

Java TCP and UDP programming

Sources (2/2)