Enrol to start learning
Reading is open to everyone. Enrolling is free, and it is what unlocks the audio lessons, practice tests and progress tracking.
18.3. TCP Programming in Java
Learn content
Interactive Audio Lesson
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
Today we are going to study TCP, or Transmission Control Protocol. It's a reliable, connection-oriented protocol widely used in networking. Does anyone know what that means?
I think it means that it ensures the delivery of data, right?
Exactly! TCP establishes a connection between the client and server, which ensures that data packets arrive in order and without errors. That’s why it’s so popular for applications where reliability is crucial, like in chat programs and web browsing.
How does it compare to UDP?
Great question! Unlike TCP, UDP, or User Datagram Protocol, is connectionless and does not guarantee delivery. This makes UDP faster but less reliable. If you want to remember this, think of TCP as a 'reliable mail service' and UDP as 'sending a postcard.'
What kind of applications commonly use TCP?
Applications like web browsers, email clients, and file transfers utilize TCP due to the need for reliable data delivery. Now, let's shift to how we implement TCP in Java.
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
We'll start with the TCP server example. In Java, we use the ServerSocket class to create our server. Can anyone recall how we set this up?
You start by creating a ServerSocket and specifying the port number?
Exactly! The line ServerSocket serverSocket = new ServerSocket(5000); sets up our server on port 5000. Let’s review the code briefly together.
What happens after that?
After that, it waits for a client to connect with serverSocket.accept(). This line blocks the server until a client connects, which is a key point in ensuring a connection is established. The server then uses input and output streams to communicate with the client.
What types of communication can we have?
Great question! Primarily, we use PrintWriter for sending messages and BufferedReader for receiving messages. In our example, you can see the echo functionality where the server simply echoes back what the client sends.
Unlock the classroom podcast
The transcript is free to read. A free account plays the conversation back.
Now, let’s talk about the TCP client. We can establish a connection to the server using the Socket class. Who can give me the correct syntax?
You use Socket socket = new Socket("localhost", 5000); right?
Exactly right! This connects to the server running on localhost at port 5000. What do you think is the next step?
We need to send messages!
Correct! We can send messages using PrintWriter, just like the server. After sending a message, we can use BufferedReader to read the server's response. Let’s run through sending 'Hello Server!' together.
And then we print the server response, right?
Absolutely! This interaction forms the basis of much TCP communication in Java applications.
Overview
Short Summary
This section covers the fundamentals of TCP programming in Java, illustrating the implementation of both client and server applications.
Medium Summary
In this section, the TCP programming model is introduced through detailed examples of a TCP server and client written in Java. The focus is on how to establish connections and handle communication between server and client applications using socket programming.
Detailed Summary
TCP Programming in Java
Overview
This section details the implementation of TCP networking in Java, specifically focusing on the creation of a TCP server and a TCP client. TCP (Transmission Control Protocol) is a connection-oriented protocol that guarantees reliable communication between devices over a network.
TCP Server Example
The provided Java example for the TCP server demonstrates how a server initializes a listening socket on port 5000, accepts client connections, and reads messages sent by clients. The server echoes back the received message to the client, showcasing basic request-response behavior typical in networked applications.
Code Example:
import java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server started...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message = in.readLine();
System.out.println("Received: " + message);
out.println("Echo: " + message);
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}Key Points:
- Uses
ServerSocketfor accepting client connections. - Uses
PrintWriterandBufferedReaderfor sending and receiving messages. - Demonstrates basic echo functionality.
TCP Client Example
The TCP client example illustrates how to connect to the server running on the same machine using localhost and port 5000. It sends a greeting message to the server and prints the server's echoed response.
Code Example:
import java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello Server!");
System.out.println("Server response: " + in.readLine());
in.close();
out.close();
socket.close();
}
}Key Points:
- Uses
Socketto connect to the server. - Sends messages using
PrintWriter. - Reads responses using
BufferedReader.
Reference YouTube Videos
Audio Book
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountimport java.net.*;
import java.io.*;
public class TCPServer {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server started...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected.");
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String message = in.readLine();
System.out.println("Received: " + message);
out.println("Echo: " + message);
in.close();
out.close();
clientSocket.close();
serverSocket.close();
}
}Detailed Explanation
The TCP Server example illustrates how to create a simple server in Java which listens for incoming connections.
- It starts by importing necessary classes for networking and I/O operations.
- The
TCPServerclass defines the server, and themainmethod is the entry point. - A
ServerSocketis created on port 5000, allowing the server to receive connections. - The
serverSocket.accept()method waits for a client to connect. Once a connection is made, aSocketfor the client is created. - The server can then read messages sent by the client through an input stream and respond using an output stream.
- Finally, it sends an echo of the received message and closes the streams and sockets, ending the connection safely.
Examples & Analogies
Think of the TCP Server as a reception desk in a hotel. Guests (clients) come in and check into the hotel. The desk (server) listens for guests, checks them in, takes their requests, and then processes them (echoes their messages) before bidding them farewell (closing connections).
Unlock the audio lesson
The script is above and free to read. A free account plays it back, in the voice you pick.
Create a free accountimport java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 5000);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("Hello Server!");
System.out.println("Server response: " + in.readLine());
in.close();
out.close();
socket.close();
}
}Detailed Explanation
The TCP Client example demonstrates how to create a simple client that connects to the server created in the previous example.
- It imports the necessary Java networking and I/O classes.
- The
TCPClientclass defines the client application, and themainmethod serves as the entry point. - The client establishes a socket connection to the server located at "localhost" on port 5000.
- It initializes output (to send messages to the server) and input (to read server responses) streams.
- The client sends a greeting message, "Hello Server!" to the server.
- It then waits for a response from the server, reads the response, and prints it to the console.
- Finally, all streams and sockets are closed to clean up resources.
Examples & Analogies
Imagine the TCP Client as a hotel guest sending a message to the reception desk (the server). The guest states, "Hello!" and waits for the receptionist to respond. After getting the response, the guest leaves the desk with a smile, having had their interaction resolved.
--
Key concepts
Core takeaways and short definitions to help you quickly recall the key ideas from this section.
- TCP:
A reliable, ordered, and error-checked delivery method for data packets.
- ServerSocket:
A class used to create server-side sockets, allowing a server to listen for incoming connections.
- Socket:
A client-side representation that connects to the server and facilitates communication.
Examples
Memory aids
When data needs to flow, TCP is the way to go. It ensures that packets arrive, keeping connections alive.
Once, a ServerSocket waited for clients to connect. It knew that each time a friend joined, it would send back a message, confirming they were heard, just like a good server should.
Flash Cards
Glossary
TCP
Transmission Control Protocol, a connection-oriented protocol that ensures reliable data transmission between devices.
ServerSocket
Class in Java for creating server-side sockets that listen for client connections.
Socket
Class in Java that represents a client-side socket used to connect to a server.