Java TCP programming

https://github.com/heig-vd-dai-course

Web · PDF

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.

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Objectives

  • Program your own TCP client/server applications in Java with the Socket API
  • Understand how to process data from streams
  • Make usage of a REPL

Your applications will be able to communicate over the network!

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Explore the code examples

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

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Explore the code examples

Individually, or in pair/group, take 10 minutes to explore and discuss the code examples.

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.

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

TCP

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

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

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)
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

The Socket API

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

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

The Socket API

  • Originally developed by Berkeley University
  • Ported to Java and many other languages
  • Provides a simple API to use TCP and UDP
  • A socket is a connection between two parties using a protocol and a port
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Client/server common functions

Operation Description
socket() Creates a new socket
getInputStream() Gets the input stream of a socket
getOutputStream() Gets the output stream of a socket
close() Closes a socket
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Client structure and functions

  1. Create a Socket
  2. Connect the socket to an IP address and a port number
  3. Read and write data from/to the socket
  4. Flush and close the socket
Operation Description
connect() Connects a socket to an IP address and a port number
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Server structure and functions

  1. Create a ServerSocket
  2. Bind the socket to an IP address and a port number
  3. Listen for incoming connections
  4. Loop
    1. Accept an incoming connection - creates a new Socket on a port
    2. Read and write data from/to the socket
    3. Flush and close the socket
  5. Close the ServerSocket
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0
Operation Description
bind() Binds a socket to an IP address and a port number
listen() Listens for incoming connections
accept() Accepts an incoming connection

To make it simple, a socket is just like a file that you can open, read from, write to and close. To exchange data, sockets on both sides must be connected.

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Processing data from streams

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

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

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
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

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);
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

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

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

// Get output stream as binary with buffer
output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream());
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Variable length data

Data sent can have a variable length. Manage this using one of the two methods:

  • Use a delimiter
  • Communicate a fixed length

This must be defined by your application protocol!

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Using a delimiter:

// End of transmission character
String EOT = "\u0004";

// Read data until the delimiter is found
String line;
while ((line = in.readLine()) != null && !line.equals(EOT)) {
  System.out.println(
    "[Server " + SERVER_ID + "] received data from client: " + line
  );
}
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Communicating a fixed length:

// Send the length of the data
out.write("DATA_LENGTH " + data.length() + "\n");

// Send the data
out.write(data);
// Read the length of the data
String[] parts = in.readLine().split(" ");
int dataLength = Integer.parseInt(parts[1]);

// Read the data
for (int i = 0; i < dataLength; i++) {
  System.out.print((char) in.read());
}
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Read-Eval-Print Loop (REPL)

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

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

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!

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Questions

Do you have any questions?

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Practical content

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

What will you do?

  • Update your application protocol with the new knowledge you gained
  • Execute the code examples and run multiple clients at the same time
  • Explore the Java TCP programming template
  • Implement and Dockerize the "Guess the number" game (optional)
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Find the practical content

You can find the practical content for this chapter on GitHub.

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

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!

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

What will you do next?

In the next chapter, you will learn the following topics:

  • Java UDP programming
    • How does it compare to TCP?
    • How to create efficient UDP network applications
    • Implement the "Temperature monitoring" application using UDP (optional)
HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0

Sources

HEIG-VD - DAI Course 2024-2025 - CC BY-SA 4.0