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.
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();
}
}
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.
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();
}
}
}
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.
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();
}
}
}
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.
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();
}
}
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.
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;
}
}
This example demonstrates a simple load balancer implementation that distributes requests among a pool of servers, ensuring efficient resource utilization and improved response times.
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"));
}
}
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.
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();
}
}
}
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.
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"));
}
}
This example illustrates how an asynchronous server can process requests concurrently using a thread pool, allowing for non-blocking operations and improved performance.
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies