Java Language – 54 – Sockets and Socket Programming

Networking – Sockets and Socket Programming
Introduction to Socket Programming

Socket programming is a fundamental aspect of network communication in Java. Sockets provide a standard interface for network communication between computers over the Internet or a local network. In this guide, we will explore the basics of socket programming in Java and demonstrate how to create a simple client-server application.

Sockets in Java

In Java, socket programming is made straightforward through the use of the java.net package. The two most commonly used types of sockets are:

  • ServerSocket: This class represents a server socket that listens for incoming connections.
  • Socket: This class represents a client socket that initiates connections to a server.
Server-Client Communication

In a typical client-server scenario, a server waits for incoming client connections. When a client connects to the server, they can exchange data. Here’s a simple example of a server and a client communicating using sockets.

Server Code

Let’s create a Java server that listens for client connections and sends a “Hello, Client!” message when a connection is established.


import java.io.*;
import java.net.*;

public class Server {
    public static void main(String[] args) {
        try {
            // Create a ServerSocket that listens on port 12345
            ServerSocket serverSocket = new ServerSocket(12345);
            System.out.println("Server is waiting for clients...");

            while (true) {
                // Accept incoming client connections
                Socket clientSocket = serverSocket.accept();
                System.out.println("Client connected from " + clientSocket.getInetAddress());

                // Create input and output streams for communication
                PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
                out.println("Hello, Client!");
                out.close();

                // Close the client socket
                clientSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Client Code

Now, let’s create a Java client that connects to the server and reads the message.


import java.io.*;
import java.net.*;

public class Client {
    public static void main(String[] args) {
        try {
            // Create a client socket and connect to the server
            Socket socket = new Socket("localhost", 12345);

            // Create an input stream to read data from the server
            BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String message = in.readLine();
            System.out.println("Message from server: " + message);

            // Close the socket
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Conclusion

Socket programming in Java is an essential skill for creating networked applications. Whether you’re building a chat application, a file transfer system, or any other networked software, understanding sockets and how to use them is crucial. The examples provided in this guide serve as a foundation for more complex network communication applications.