Prerequisites : Socket Programming in Java
This article assumes that you have basic knowledge of socket programming in java and the basic details of client-server model used in communication.
Why to use threads in network programming?
The reason is simple, we don’t want only a single client to connect to server at a particular time but many clients simultaneously. We want our architecture to support multiple clients at the same time. For this reason, we must use threads on server side so that whenever a client request comes, a separate thread can be assigned for handling each request.
Let us take an example, suppose a Date-Time server is located at a place, say X. Being a generic server, it does not serve any particular client, rather to a whole set of generic clients. Also suppose at a particular time, two requests arrives at the server. With our basic server-client program, the request which comes even a nano-second first would be able to connect to the server and the other request would be rejected as no mechanism is provided for handling multiple requests simultaneously. To overcome this problem, we use threading in network programming.
The following article will focus on creating a simple Date-Time server for handling multiple client requests at the same time.
As normal, we will create two java files,Server.java and Client.java. Server file contains two classes namely Server (public class for creating server) and ClientHandler (for handling any client using multithreading). Client file contain only one public class Client (for creating a client). Below is the flow diagram of how these three classes interact with each other.
Server Side Programming(Server.java)
- Server class : The steps involved on server side are similar to the article Socket Programming in Java with a slight change to create the thread object after obtaining the streams and port number.
- Establishing the Connection: Server socket object is initialized and inside a while loop a socket object continuously accepts incoming connection.
- Obtaining the Streams: The inputstream object and outputstream object is extracted from the current requests’ socket object.
- Creating a handler object: After obtaining the streams and port number, a new clientHandler object (the above class) is created with these parameters.
- Invoking the start() method : The start() method is invoked on this newly created thread object.
- ClientHandler class : As we will be using separate threads for each request, lets understand the working and implementation of the ClientHandler class extending Threads. An object of this class will be instantiated each time a request comes.
- First of all this class extends Thread so that its objects assumes all properties of Threads.
- Secondly, the constructor of this class takes three parameters, which can uniquely identify any incoming request, i.e. a Socket, a DataInputStream to read from and a DataOutputStream to write to. Whenever we receive any request of client, the server extracts its port number, the DataInputStream object and DataOutputStream object and creates a new thread object of this class and invokes start() method on it.
Note : Every request will always have a triplet of socket, input stream and output stream. This ensures that each object of this class writes on one specific stream rather than on multiple streams.
- Inside the run() method of this class, it performs three operations: request the user to specify whether time or date needed, read the answer from input stream object and accordingly write the output on the output stream object.
A new client is connected : Socket[addr=/127.0.0.1,port=60536,localport=5056] Assigning new thread for this client Client Socket[addr=/127.0.0.1,port=60536,localport=5056] sends exit... Closing this connection. Connection closed
Client Side Programming (Client.java)
Client side programming is similar as in general socket programming program with the following steps-
- Establish a Socket Connection
What do you want?[Date | Time].. Type Exit to terminate connection. Date 2017/06/16 What do you want?[Date | Time].. Type Exit to terminate connection. Time 05:35:28 What do you want?[Date | Time].. Type Exit to terminate connection. Geeks Invalid input What do you want?[Date | Time].. Type Exit to terminate connection. Exit Closing this connection : Socket[addr=localhost/127.0.0.1,port=5056,localport=60536] Connection closed
How these programs works together?
- When a client, say client1 sends a request to connect to server, the server assigns a new thread to handle this request. The newly assigned thread is given the access to streams for communicating with the client.
- After assigning the new thread, the server via its while loop, again comes into accepting state.
- When a second request comes while first is still in process, the server accepts this requests and again assigns a new thread for processing it. In this way, multiple requests can be handled even when some requests are in process.
How to test the above program on your system?
Save the two programs in same package or anywhere. Then first run the Server.java followed by the Client.java. You can either copy the client program in two three separate files and run them individually, or if you have an IDE like eclipse, run multiple instances from the same program. The output shown above is from a single client program, the similar results will be achieved if multiple clients are used.
Next: Multi-threaded chat Application : Server Side Programming , Client Side Programming
This article is contributed by Rishabh Mahrsee. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Socket Programming in Java
- Difference Between Daemon Threads and User Threads In Java
- Killing threads in Java
- Joining Threads in Java
- Output of Java program | Set 16 (Threads)
- Producer-Consumer solution using threads in Java
- Understanding threads on Producer Consumer Problem | Java
- Green vs Native Threads and Deprecated Methods in Java
- Java tricks for competitive programming (for Java 8)
- Print 1 2 3 infinitely using threads in C
- Two way communication between Client and Server using Win32 Threads
- Maximum number of threads that can be created within a process in C
- Java Programming Basics
- Comparison of Java with other programming languages
- Functional Programming in Java with Examples
- Beginning Java programming with Hello World Example
- Which Java libraries are useful for competitive programming?
- Fast I/O in Java in Competitive Programming
- Different Approaches to Concurrent Programming in Java
- The complete History of Java Programming Language