Client-Server Communication in Java
Introduction
Client-server communication is a model in which the client sends requests to a server, and the server responds with data. Java provides built-in support for client-server communication through the java.net
package. In this tutorial, we will create a simple client-server application where the client sends a message to the server, and the server processes it and sends a response back.
The client communicates with the server using Socket
for sending requests, and the server uses ServerSocket
to listen for incoming connections.
Step 1: Create the Server
The server is responsible for listening for incoming connections from clients and responding to their requests. The server uses the ServerSocket
class to listen on a specific port.
Example 1: Server Code
import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try { // Create a ServerSocket to listen on port 1234 ServerSocket serverSocket = new ServerSocket(1234); System.out.println("Server started, waiting for client..."); // Wait for a client to connect Socket clientSocket = serverSocket.accept(); System.out.println("Client connected!"); // Set up input and output streams for communication BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); // Read message from client String message = in.readLine(); System.out.println("Received from client: " + message); // Send response to client out.println("Hello from server!"); // Close the streams and socket in.close(); out.close(); clientSocket.close(); serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } }
In this example:
- We create a
ServerSocket
to listen for incoming connections on port 1234. - The server waits for a client to connect using
accept()
method. - Once a client connects, the server reads the message from the client and sends a response.
- Finally, the server closes the input/output streams and the socket.
Step 2: Create the Client
The client is responsible for connecting to the server, sending a message, and receiving a response. The client uses the Socket
class to establish a connection to the server.
Example 2: Client Code
import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { try { // Create a Socket to connect to the server at localhost on port 1234 Socket socket = new Socket("localhost", 1234); // Set up input and output streams BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); // Send a message to the server out.println("Hello from client!"); // Read response from the server String response = in.readLine(); System.out.println("Received from server: " + response); // Close the streams and socket in.close(); out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
In this example:
- We create a
Socket
to connect to the server atlocalhost
on port 1234. - The client sends a message to the server using a
PrintWriter
. - The client waits for the response from the server using a
BufferedReader
. - Finally, the client closes the input/output streams and the socket.
Step 3: Running the Server and Client
To run the server and client applications:
- First, run the
Server
class. The server will start and wait for client connections. - Next, run the
Client
class. The client will connect to the server, send a message, and print the response from the server.
Understanding the Communication Flow
The flow of communication between the client and the server in this example is as follows:
- The client creates a socket and connects to the server at
localhost
on port 1234. - The server listens for incoming connections using
ServerSocket.accept()
method. - Once the client connects, the server reads the message from the client and sends a response.
- The client receives the server's response and prints it to the console.
Exception Handling in Client-Server Communication
It's important to handle exceptions properly in client-server communication, as network operations can fail due to various reasons like timeouts or connectivity issues. Some common exceptions to handle include:
IOException
: This exception occurs if there's an error in input or output operations (e.g., reading from or writing to a socket).UnknownHostException
: This exception occurs if the client cannot resolve the server's host name to an IP address.SocketException
: This exception occurs if there's an error in socket communication (e.g., the connection is interrupted).
Always handle these exceptions to ensure that your application remains stable even when network issues occur.
Conclusion
In this tutorial, we learned how to set up client-server communication in Java. We created a simple server and client application using ServerSocket
and Socket
classes. The client sends a message to the server, and the server responds with a message.
- We covered how to create the server, listen for client connections, and send responses.
- We also saw how the client connects to the server, sends a request, and receives a response.