Java > Java Networking > Socket Programming > Creating TCP and UDP Sockets
Java TCP Socket Example
This snippet demonstrates how to create a simple TCP socket to establish a connection between a client and a server in Java. TCP provides a reliable, ordered, and error-checked stream of bytes between applications over an IP network.
Server-Side Code (TCP)
This code creates a `ServerSocket` that listens for incoming client connections on a specified port (12345 in this case). When a client connects, the server accepts the connection, creates a `Socket` object for communication, sends a greeting message, and closes the client socket. The `while(true)` loop allows the server to accept multiple client connections.
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws IOException {
int port = 12345; // Port number
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server listening on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println("Hello from the server!");
clientSocket.close();
}
}
}
Client-Side Code (TCP)
This code creates a `Socket` object that connects to the server at the specified address and port. It then reads a message from the server and prints it to the console. Finally, it closes the socket.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class TCPClient {
public static void main(String[] args) throws IOException {
String serverAddress = "localhost"; // Server IP address
int port = 12345; // Server port
Socket socket = new Socket(serverAddress, port);
System.out.println("Connected to server.");
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = input.readLine();
System.out.println("Server says: " + message);
socket.close();
}
}
Concepts Behind the Snippet
TCP (Transmission Control Protocol) is a connection-oriented protocol that provides reliable data transfer between applications. It establishes a connection before sending data, ensures data is delivered in the correct order, and provides error checking and recovery mechanisms. A Socket is an endpoint of a two-way communication link between two programs running on the network. ServerSocket waits for incoming client request, then accepts the connection. Then client socket will create a connection to the server.
Real-Life Use Case
TCP sockets are commonly used for web servers (HTTP/HTTPS), email servers (SMTP/IMAP/POP3), and file transfer protocols (FTP/SFTP) where reliable data transfer is crucial.
Best Practices
Always handle `IOExceptions` properly to prevent your application from crashing due to network issues. Use try-with-resources statements to ensure that sockets are closed properly, even if exceptions occur. Consider using thread pools for handling multiple client connections concurrently on the server side.
Interview Tip
Be prepared to explain the difference between TCP and UDP. TCP is connection-oriented and reliable, while UDP is connectionless and unreliable. Also, understand the socket lifecycle (creation, connection, data transfer, disconnection).
When to Use Them
Use TCP when reliable data transfer is essential, such as financial transactions, web browsing, or file transfers. If a single packet drop is critical, chose TCP.
Memory Footprint
TCP sockets have a higher memory footprint compared to UDP due to the connection management overhead and buffering requirements.
Alternatives
Alternatives to raw TCP sockets include using higher-level libraries or frameworks like Netty or Spring Integration, which provide more abstractions and simplify network programming.
Pros
Cons
FAQ
-
What is the difference between a Socket and a ServerSocket?
A `ServerSocket` listens for incoming connection requests from clients. A `Socket` represents a single connection between a client and a server after the connection has been established. -
How do I handle multiple clients connecting to my server?
You can use threads or an ExecutorService to handle each client connection in a separate thread. This allows your server to handle multiple clients concurrently.