ABC’s Of Client-Server Architecture (Bonus :-Included Implementation)

WTF !!!

If you are a web programmer, you should heard about what is a client-server architecture. Almost all times we create web-applications for different purposes. but do you know how web services handle multiple requests , how they utilize resources. if you don’t have a deep understand about those things, this is the place to start your learning.

In this blog, i’m going to create a java based TCP web server and TCP client by implementing basic functionalities of a web server.

Topics are covered in this blog

  • What is a client server architecture
  • What is TCP/UDP
  • How to write a java based web server
  • How to write a java based client

What is client server architecture

this is basically consist of two models , simply client communicating with the server in order to perform services.

If you don’t know deep details, i’m going to mention the best blog i found about these topics. Read that and come back.(Don’t forget to read the rest of my blog)

Communication Protocols (TCP/UDP)

There is two types of protocols which we can use for socket programming.

  • TCP/IP
  • UDP/IP

UDP — User data diagram protocol

this protocol is basically connection less protocol. which means this communication doesn't care about the guaranteed delivery of the data. This protocol is widely used for gaming and online streaming because in gaming and streaming its not creating significant change at the user end if the communication breaks for a moment.

This protocol is speedy than TCP/IP which using windowing technology to ensure all packets are delivered successfully

TCP/IP — Transmission control protocol

This protocol is almost everything. in modern day internet running on top of this protocol. HTTP , HTTPS transports are driven by this protocol and it’s ensure the gurantee of delivering packets between the server and client.

How TCP/IP ensure guaranteed delivery

Please watch below video if you are curios about how its happening.

How to write a java based web server

Okay it’s time to get hands dirty. Let’s see how can we write a java based server by implementing a socket.

Sub topics -

  • Thread pool
  • Queue
  • Executor
  • Web Socket

Before describe everything, please go to my GIT repository mentioned below and study about it a little bit. Because i’m going to what happened in code according to the topics mentioned above.

Download the project and build using maven, use the script files to run the client and server. all instructions are included in md file.

Web Socket

In order to listen to the clients we have to open a socket and by using below mentioned code.

public void run() {

ThreadPool threadPool = new ThreadPool(queueSize, nThread);

openServerSocket();
while (true) {
Socket clientSocket = null;
try {
clientSocket = this.serverSocket.accept();
} catch (IOException e) {
throw new RuntimeException(
"Error accepting client connection", e);
}

try {
threadPool.submitTask(new Request(clientSocket, WaitTime));
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

private void openServerSocket() {
try {
this.serverSocket = new ServerSocket(this.serverPort);
System.out.println("Server Started and listning to port" + this.serverPort);
} catch (IOException e) {
throw new RuntimeException("Cannot open port " + this.serverPort, e);
}
}

For a given specific port its create a web socket and listening to a client.

Thread Pool

It’s inefficient if we use single thread to handle all the requests from the clients. practically in real world scenarios, that is impossible. because if the server had concurrent request to process, some clients has to waits forever util first requests to finish.

To avoid that we create thread pool to handle requests.

public ThreadPool(int queueSize, int nThread) {
queue = new LinkedListQueue(queueSize);

String threadName = null;
Executor task = null;

for (int count = 0; count < nThread; count++) {
threadName = "Thread-" + count;
task = new Executor(queue);
Thread thread = new Thread(task, threadName);
thread.start();
}
}

Above mentioned code create n number of threads and run the Executor class using the thread.

Executor

public void run() {
try {
while (true) {
String name = Thread.currentThread().getName();
Runnable task = queue.dequeue();
System.out.println("Task Started by Thread : " + name);
task.run();
System.out.println("Task Finished by Thread : " + name);
}
} catch (InterruptedException e) {
e.printStackTrace();
}

}

Executor class is designed to run a queue.dequeue() method in LinkedList Queue class, this dequeue method is implemented to wait for a client request work task. Other wise it will wait for a task to be submitted.

Queue

public synchronized Runnable dequeue()
throws InterruptedException {
while (this.queue.size() == EMPTY) {
wait();
}
if (this.queue.size() == this.MAX_TASK_IN_QUEUE) {
notifyAll();
}
return this.queue.poll();
}

So when a request coming to the server it is pushed to the queue, all the threads are waiting for a client request task and once the task enqueued to the queue one of the thread will handle the task and perform a output to the client.

public void submitTask(Runnable task) throws InterruptedException {
queue.enqueue(task);
}

I think most of people don’t understand what i’m saying in above if you haven’t touched these concepts before. Please go through the code carefully few times and try to understand the flow.

Don’t give up until you know it ;-)

How to write a java based client

This is how you going to write a simple client. If you could understand the server. now you can handle the client by your self ;-).

public void run() {

String sentence;
String modifiedSentence = null;
Socket clientSocket = null;
try {

clientSocket = new Socket("localhost", port);
//Send the message to the server
OutputStream os = clientSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);

String clientMessage = "Message " + Math.random() ;

String sendMessage = clientMessage + "\n";
bw.write(sendMessage);
bw.flush();
System.out.println("Message sent to the server : "+sendMessage);

//Get the return message from the server
InputStream is = clientSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();

System.out.println("FROM SERVER: " + message);


} catch (IOException e) {
e.printStackTrace();
}

}

Here again i provide my GIT repository URL of above project. Download the project and build using maven, use the script files to run the client and server. all instructions are included in md file.

Almost finished my third blog, if you have read this far i love you with my heart =D , don’t forget to love me back.