Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Introducing Threads in Socket Programming in Java
Next article icon

Introducing Threads in Socket Programming in Java

Last Updated : 08 Feb, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report
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.

Quick Overview

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. Date-time-server-1

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.
    1. Establishing the Connection: Server socket object is initialized and inside a while loop a socket object continuously accepts incoming connection.
    2. Obtaining the Streams: The inputstream object and outputstream object is extracted from the current requests' socket object.
    3. Creating a handler object: After obtaining the streams and port number, a new clientHandler object (the above class) is created with these parameters.
    4. 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.
    1. First of all this class extends Thread so that its objects assumes all properties of Threads.
    2. 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.
    3. 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.
Java
// Java implementation of  Server side // It contains two classes : Server and ClientHandler // Save file as Server.java  import java.io.*; import java.text.*; import java.util.*; import java.net.*;  // Server class public class Server  {     public static void main(String[] args) throws IOException      {         // server is listening on port 5056         ServerSocket ss = new ServerSocket(5056);                  // running infinite loop for getting         // client request         while (true)          {             Socket s = null;                          try              {                 // socket object to receive incoming client requests                 s = ss.accept();                                  System.out.println("A new client is connected : " + s);                                  // obtaining input and out streams                 DataInputStream dis = new DataInputStream(s.getInputStream());                 DataOutputStream dos = new DataOutputStream(s.getOutputStream());                                  System.out.println("Assigning new thread for this client");                  // create a new thread object                 Thread t = new ClientHandler(s, dis, dos);                  // Invoking the start() method                 t.start();                              }             catch (Exception e){                 s.close();                 e.printStackTrace();             }         }     } }  // ClientHandler class class ClientHandler extends Thread  {     DateFormat fordate = new SimpleDateFormat("yyyy/MM/dd");     DateFormat fortime = new SimpleDateFormat("hh:mm:ss");     final DataInputStream dis;     final DataOutputStream dos;     final Socket s;           // Constructor     public ClientHandler(Socket s, DataInputStream dis, DataOutputStream dos)      {         this.s = s;         this.dis = dis;         this.dos = dos;     }      @Override     public void run()      {         String received;         String toreturn;         while (true)          {             try {                  // Ask user what he wants                 dos.writeUTF("What do you want?[Date | Time]..\n"+                             "Type Exit to terminate connection.");                                  // receive the answer from client                 received = dis.readUTF();                                  if(received.equals("Exit"))                 {                      System.out.println("Client " + this.s + " sends exit...");                     System.out.println("Closing this connection.");                     this.s.close();                     System.out.println("Connection closed");                     break;                 }                                  // creating Date object                 Date date = new Date();                                  // write on output stream based on the                 // answer from the client                 switch (received) {                                      case "Date" :                         toreturn = fordate.format(date);                         dos.writeUTF(toreturn);                         break;                                              case "Time" :                         toreturn = fortime.format(date);                         dos.writeUTF(toreturn);                         break;                                              default:                         dos.writeUTF("Invalid input");                         break;                 }             } catch (IOException e) {                 e.printStackTrace();             }         }                  try         {             // closing resources             this.dis.close();             this.dos.close();                      }catch(IOException e){             e.printStackTrace();         }     } } 
Output
  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-
  1. Establish a Socket Connection
  2. Communication
Java
// Java implementation for a client // Save file as Client.java  import java.io.*; import java.net.*; import java.util.Scanner;  // Client class public class Client  {     public static void main(String[] args) throws IOException      {         try         {             Scanner scn = new Scanner(System.in);                          // getting localhost ip             InetAddress ip = InetAddress.getByName("localhost");                  // establish the connection with server port 5056             Socket s = new Socket(ip, 5056);                  // obtaining input and out streams             DataInputStream dis = new DataInputStream(s.getInputStream());             DataOutputStream dos = new DataOutputStream(s.getOutputStream());                  // the following loop performs the exchange of             // information between client and client handler             while (true)              {                 System.out.println(dis.readUTF());                 String tosend = scn.nextLine();                 dos.writeUTF(tosend);                                  // If client sends exit,close this connection                  // and then break from the while loop                 if(tosend.equals("Exit"))                 {                     System.out.println("Closing this connection : " + s);                     s.close();                     System.out.println("Connection closed");                     break;                 }                                  // printing date or time as requested by client                 String received = dis.readUTF();                 System.out.println(received);             }                          // closing resources             scn.close();             dis.close();             dos.close();         }catch(Exception e){             e.printStackTrace();         }     } } 
Output :
  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?

  1. 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.
  2. After assigning the new thread, the server via its while loop, again comes into accepting state.
  3. 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  

Next Article
Introducing Threads in Socket Programming in Java

R

Rishabh Mahrsee
Improve
Article Tags :
  • Java
Practice Tags :
  • Java

Similar Reads

    Socket Programming in Java
    Socket programming in Java allows different programs to communicate with each other over a network, whether they are running on the same machine or different ones. This article describes a very basic one-way Client and Server setup, where a Client connects, sends messages to the server and the serve
    6 min read
    Multi-threaded Chat Application in Java | Set 2 (Client Side Programming)
    Prerequisites : Introducing threads in socket programming, Multi-threaded chat Application | Set 1 This article gives the implementation of client program for the multi-threaded chat application. Till now all examples in socket programming assume that client first sends some information and then ser
    5 min read
    Multi-threaded chat Application in Java | Set 1 (Server Side Programming)
    Prerequisites : Introducing threads in socket programmingIn the above article, a simple date time server was created which handled multiple user requests at the same time using threading. It explains the basic concepts of threading in network programming. The same concepts can be used with very slig
    5 min read
    Transfer the File "Client Socket to Server Socket" in Java
    Prerequisites: Socket Programming in JavaFile Handling in JavaThis article describes a one-way client and Server Setup where a client connects, and sends the file to the server and the server writes the file in another location with a different name. It means we send the file using the server socket
    4 min read
    Introduction to Java NIO with Examples
    Java IO(Input/Output) is used to perform read and write operations. The java.io package contains all the classes required for input and output operation. Whereas, Java NIO (New IO) was introduced from JDK 4 to implement high-speed IO operations. It is an alternative to the standard IO API’s. In this
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences