WikiGalaxy

Personalize

Client-Server Architecture

Overview:

Client-Server Architecture is a computing model that divides tasks or workloads between service providers, called servers, and service requesters, called clients. It is a core concept in network computing and forms the backbone of modern internet applications.

Key Components:

  • Clients: Devices or applications that request services or resources from a server.
  • Servers: Systems that provide services or resources to clients.
  • Network: The medium through which clients and servers communicate.

Advantages:

  • Centralized Resources: Easy management and updating of data.
  • Scalability: Servers can be upgraded to handle more clients.
  • Security: Centralized control over data access and integrity.

Disadvantages:

  • Single Point of Failure: Server downtime affects all clients.
  • Network Dependency: Requires a stable network connection.

Example: Basic Client-Server Communication

Concept:

In a basic client-server communication setup, a client sends a request to the server, and the server processes this request and sends back a response.


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

        class Server {
            public static void main(String[] args) throws IOException {
                ServerSocket serverSocket = new ServerSocket(6666);
                Socket socket = serverSocket.accept();
                DataInputStream dis = new DataInputStream(socket.getInputStream());
                String str = dis.readUTF();
                System.out.println("Message from client: " + str);
                serverSocket.close();
            }
        }

        class Client {
            public static void main(String[] args) throws IOException {
                Socket socket = new Socket("localhost", 6666);
                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                dos.writeUTF("Hello Server");
                dos.flush();
                dos.close();
                socket.close();
            }
        }
        

Explanation:

This example demonstrates a simple client-server communication where the server listens on a port and the client connects to it, sending a message. The server receives and prints this message.

Example: Multi-threaded Server

Concept:

A multi-threaded server can handle multiple client requests simultaneously, improving efficiency and responsiveness.


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

        class MultiThreadServer {
            public static void main(String[] args) throws IOException {
                ServerSocket serverSocket = new ServerSocket(6666);
                while (true) {
                    Socket socket = serverSocket.accept();
                    new ClientHandler(socket).start();
                }
            }
        }

        class ClientHandler extends Thread {
            final Socket socket;
            
            ClientHandler(Socket socket) {
                this.socket = socket;
            }

            public void run() {
                try {
                    DataInputStream dis = new DataInputStream(socket.getInputStream());
                    String str = dis.readUTF();
                    System.out.println("Message from client: " + str);
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        

Explanation:

This example shows a server that can handle multiple clients by spawning a new thread for each client connection. This allows simultaneous processing of multiple client requests.

Example: HTTP Server

Concept:

An HTTP server responds to HTTP requests from clients, typically web browsers, to serve web pages and other resources.


        import com.sun.net.httpserver.HttpServer;
        import com.sun.net.httpserver.HttpHandler;
        import com.sun.net.httpserver.HttpExchange;
        import java.io.IOException;
        import java.io.OutputStream;
        import java.net.InetSocketAddress;

        public class SimpleHttpServer {
            public static void main(String[] args) throws IOException {
                HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
                server.createContext("/test", new MyHandler());
                server.setExecutor(null);
                server.start();
            }

            static class MyHandler implements HttpHandler {
                public void handle(HttpExchange t) throws IOException {
                    String response = "This is the response";
                    t.sendResponseHeaders(200, response.length());
                    OutputStream os = t.getResponseBody();
                    os.write(response.getBytes());
                    os.close();
                }
            }
        }
        

Explanation:

This example demonstrates a simple HTTP server using Java's HttpServer class. The server listens on port 8000 and responds with a static message to any request made to the "/test" path.

Example: Secure Client-Server Communication

Concept:

Secure communication between client and server often involves encryption protocols like SSL/TLS to protect data in transit.


        import javax.net.ssl.*;
        import java.io.*;
        import java.security.KeyStore;

        public class SecureServer {
            public static void main(String[] args) throws Exception {
                KeyStore keyStore = KeyStore.getInstance("JKS");
                keyStore.load(new FileInputStream("server.keystore"), "password".toCharArray());
                KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                kmf.init(keyStore, "password".toCharArray());
                SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(kmf.getKeyManagers(), null, null);
                SSLServerSocketFactory ssf = sc.getServerSocketFactory();
                SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(8443);
                SSLSocket c = (SSLSocket) s.accept();
                BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
                System.out.println("Received: " + in.readLine());
                s.close();
            }
        }
        

Explanation:

This example illustrates a basic secure server setup using Java's SSL/TLS support. It demonstrates how to set up an SSL server socket that listens for secure connections on port 8443.

Example: Load Balancing in Client-Server Architecture

Concept:

Load balancing is a technique used to distribute incoming network traffic across multiple servers to ensure no single server becomes overwhelmed.


        import java.util.concurrent.*;
        import java.util.*;

        class LoadBalancer {
            private final Queue servers;
            private final ExecutorService executor;

            LoadBalancer(List serverList) {
                this.servers = new LinkedList<>(serverList);
                this.executor = Executors.newFixedThreadPool(servers.size());
            }

            public void handleRequest(Request request) {
                Server server = servers.poll();
                executor.submit(() -> server.process(request));
                servers.offer(server);
            }
        }

        class Server {
            public void process(Request request) {
                System.out.println("Processing request: " + request.getData());
            }
        }

        class Request {
            private final String data;

            Request(String data) {
                this.data = data;
            }

            public String getData() {
                return data;
            }
        }
        

Explanation:

This example demonstrates a simple load balancer implementation that distributes requests among a pool of servers, ensuring efficient resource utilization and improved response times.

Example: Caching in Client-Server Architecture

Concept:

Caching is a technique used to store copies of frequently accessed data in a temporary storage location to reduce data retrieval times and improve performance.


        import java.util.*;

        class Cache {
            private final Map cacheMap = new HashMap<>();

            public String getData(String key) {
                return cacheMap.getOrDefault(key, "Data not found in cache");
            }

            public void putData(String key, String value) {
                cacheMap.put(key, value);
            }
        }

        class Client {
            public static void main(String[] args) {
                Cache cache = new Cache();
                cache.putData("1", "Cached Data 1");
                System.out.println(cache.getData("1"));
                System.out.println(cache.getData("2"));
            }
        }
        

Explanation:

This example illustrates a simple caching mechanism where data is stored in a map for quick retrieval. If the requested data is not in the cache, a default message is returned.

Example: Database Integration in Client-Server Architecture

Concept:

Database integration in client-server architecture involves connecting the server to a database to store and retrieve persistent data efficiently.


        import java.sql.*;

        public class DatabaseServer {
            public static void main(String[] args) {
                try {
                    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
                    Statement stmt = conn.createStatement();
                    ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
                    while (rs.next()) {
                        System.out.println(rs.getString("column_name"));
                    }
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        

Explanation:

This example demonstrates how a server can connect to a MySQL database using JDBC, execute a query, and process the results. This is a common scenario in web applications that require persistent data storage.

Example: Asynchronous Communication

Concept:

Asynchronous communication allows clients and servers to communicate without waiting for each other, improving application performance and responsiveness.


        import java.util.concurrent.*;

        class AsyncServer {
            private final ExecutorService executor = Executors.newFixedThreadPool(10);

            public void handleRequest(Runnable request) {
                executor.submit(request);
            }
        }

        class Client {
            public static void main(String[] args) {
                AsyncServer server = new AsyncServer();
                server.handleRequest(() -> System.out.println("Processing request asynchronously"));
            }
        }
        

Explanation:

This example illustrates how an asynchronous server can process requests concurrently using a thread pool, allowing for non-blocking operations and improved performance.

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025