Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Socket Programming in Java: A Brief Guide

Updated on 29 September, 2022

5.87K+ views

In Java, socket programming is a means to communicate across programs and stay connected to different JREs — both connection-oriented servers and non-connection-oriented servers. A Java server socket is used exclusively to initiate and process the communication between a server and a client.

This blog will cover everything there is to know about socket programming.

Socket Programming in Java

Socket programming is the process of complementing and using separate network nodes in an interactive manner. It’s a two-way communication system in which one socket (node) listens on a specific port at an IP address while the other socket connects.

Sockets in Java

In Java, sockets are one end of a two-way communication channel that connects two networked programs. The TCP layer is used to assign a port number to the given Java socket to identify the application to which we are transferring data. We use the combination of an IP address and a port number to create an endpoint.

The Java platform includes a class called Socket, which implements one side of a two-way network connection between your Java application and another program. The class sits on top of a platform-independent implementation, shielding your Java program from system-specific details.

By using the class instead of a certain native code, your Java programs may communicate over the network in a platform-independent manner.

In addition, java.net includes the ServerSocket class, which implements a socket that servers can use to listen for and accept connections from clients. This is an example that shows how to use the ServerSocket classes and Socket.

Between the client-side port and the server-side port, a connection is created.

Establishing a Java Socket Connection [CLIENT SIDE]

Before continuing with client-side programming, the client should wait for the initiation of the server. Once up and running, it will start sending queries to the Java server. The client will then wait for the server’s response. This is a good summary of the client-server connection logic. 

Let’s look into client-side programming in more detail.

To connect to another machine, you’ll need a socket connection. The two computers must know where they are on the network (IP Address) and which TCP port they are utilising to establish a socket connection. The java.net framework denotes the socket class.

The IP address of the server is the first input argument. The TCP Port is the next parameter here. (It’s nothing more than a number that tells which program should be started on a server.) HTTP, for instance, uses port 80. Usually, the range of the port numbers lie from 0 to 65535.

Communication

Streams are utilised for data input and output when communicating via a socket connection. After you have sent the requests and established a strong connection, you must shut the socket connection off.

Closing a Java Server Socket Connection

The socket connection is explicitly closed after sending the message to the server, the socket connection is explicitly closed.

// Demo Java program for Clientele

import java.net.*;

import java.io.*;

 

public class Client_Side_Program

{

    // for  initializing socket streams, input streams, and output streams

    private Socket socket        = null;

    private DataInputStream  input   = null;

    private DataOutputStream out = null;

 

    // constructor to put TCP port and IP address

    public Client(String add, int port)

    {

        // establish a connection

        try

        {

            socket = new Socket(add, port);

            System.out.println(“Connected”);

 

            // takes input from terminal

            input  = new DataInputStream(System.in);

 

            // sends output to the socket

            out = new DataOutputStream(socket.getOutputStream());

        }

        catch(UnknownHostException u)

        {

            System.out.println(u);

        }

        catch(IOException i)

        {

            System.out.println(i);

        }

 

        // string to read message from input

        String line = “”;

 

        // keep reading until “Over” is input

        while (!line.equals(“Over”))

        {

            try

            {

                line = input.readLine();

                out.writeUTF(line);

            }

            catch(IOException i)

            {

                System.out.println(i);

            }

        }

 

        // close the connection

        try

        {

            input.close();

            out.close();

            socket.close();

        }

        catch(IOException i)

        {

            System.out.println(i);

        }

    }

 

    public static void main(String args[])

    {

        Client client = new Client(“127.0.0.1”, 5000);

    }

}

To visit the source of this code, click here

Establishing a Java Socket Connection [SERVER SIDE]

The server creates its object and awaits the client’s request while considering the Java server socket side connection. The server will interact with the client once the request has been sent. You’ll need two sockets to code the server-side application, which is as follows – when a client creates a new Socket(), a ServerSocket is created to wait for client requests. A simple socket can be defined as a program that initiates server-side communication with the client. You can communicate the responses with the client accordingly, once you get the report from the java server-side socket connection.

Communication

To use the socket for sending output, we generally look forward to using the getOutputStream() method.

Closing a Java Server Socket Connection

It is crucial to finish the connection by switching off both the socket and the input-output streams.

// A Server java program

import java.net.*;

import java.io.*;

 

public class Server

{

    //initialize socket and input stream

    private Socket      socket   = null;

    private ServerSocket server   = null;

    private DataInputStream in   =  null;

 

    // constructor with port

    public Server(int port)

    {

        //  waits for a connection after starting a server

        try

        {

            server = new ServerSocket(port);

            System.out.println(“Server: started”);

 

            System.out.println(“Waiting for the arrival of a client …”);

 

            socket = server.accept();

            System.out.println(“Client has been accepted”);

 

            // for taking client socket input

            in = new DataInputStream(

                new BufferedInputStream(socket.getInputStream()));

 

            String line = “”;

 

            // for reading message from client until “Over” is sent

            while (!line.equals(“Over”))

            {

                try

                {

                    line = in.readUTF();

                    System.out.println(line);

 

                }

                catch(IOException i)

                {

                    System.out.println(i);

                }

            }

            System.out.println(“Closing connection”);

 

            // close connection

            socket.close();

            in.close();

        }

        catch(IOException i)

        {

            System.out.println(i);

        }

    }

 

    public static void main(String args[])

    {

        Server server = new Server(5000);

    }

}

To check details of this code, click here.

You can run the server-side software first after configuring both the client and server ends. Then, you must execute the client-side software and send the request. The server will react immediately when the request comes from the client end.

Terminal or Command Prompt Running 

To initiate the Terminal or Command Prompt, we will make use of the following commands. To begin with, we will create two windows, one will be dedicated for the server and the other for the client.

  1. Let the Server program start running. 

$ java Server 

  1. Then, in a different terminal, launch the Client application as,

java client $

The software will show “Connected” and “Client Accepted” as the server accepts the client.

  1. In the Client box, you can then begin entering messages. Here’s an example of a Client input.

Hi! This marks my first professional socket connection. 

Which the Server gets and displays at the same time

Hi! This marks my first professional socket connection. 

Over.

Closing  connection

As previously stated, sending “Over” ends the connection between the Client and the Server.

Conclusion 

Java Socket programming is an essential tool that proceeds by using socket APIs to establish communication between local and remote client-server applications. Proper knowledge of socket programming can improve server and client to and fro connections.

If you’re looking to learn Java and master full-stack development, we have just the high-impact course for you: upGrad’s Executive PG Programme in Software Development – Specialization in Full Stack Development

The 13-months program from IIIT-B is designed to help students acquire skills such as Fundamentals of Computer Science, Software Development Processes, Backend APIs, and Interactive Web UI. You get access to a Software Career Transition Bootcamp both for non-tech and new coders to hone their programming skills and 360° career support from upGrad. 

Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.

Frequently Asked Questions (FAQs)

1. What are the benefits of learning Java socket programming?

Sockets might be used to construct a client-server application, such as a chat, from a networking standpoint. Sockets are implemented at the most basic level of security to discover if a system's ports are open, whether there are standard port scanner programs like Nmap and if they can be utilised at a low level. They can be used in the same manner as the SSH - Secure Socket Shell command can be used to connect to an external server via a reverse shell.

2. What does the accept function do?

The accept function waits for a client to connect to the server by blocking staying there until an argument arrives. Then we use the getInputStream function to get input from the socket. The server is designed such that it continues to accept sent messages until the Over command is received.

3. Why are threads used in network programming?

We want several clients to join at the same time. So, we must employ threads on the server side so that a different thread may handle each client request. Let’s assume a situation where two requests come at the server simultaneously. As no method for processing multiple requests simultaneously is given in our simple server-client application, the request that arrives even a nanosecond early will be able to connect to the server, while the other request will be refused.

RELATED PROGRAMS