Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconSocket Programming in Java: A Brief Guide

Socket Programming in Java: A Brief Guide

Last updated:
21st May, 2022
Views
Read Time
7 Mins
share image icon
In this article
Chevron in toc
View All
Socket Programming in Java: A Brief Guide

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.

Ads of upGrad blog

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.

Explore our Popular Software Engineering Courses

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.

Read our Popular Articles related to Software Development

 

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.

Ads of upGrad blog

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.

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1What 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.

2What 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.

3Why 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.

Explore Free Courses

Suggested Blogs

What is Composition in Java With Examples
65133
Java is a versatile language that supports object-oriented programming and code reusability with building relationships between two classes. There are
Read More

by Arjun Mathur

19 Feb 2024

Software Engineer / Developer Salary in India in 2024 [For Freshers & Experienced]
907290
Summary: In this article, you will learn about Software Engineer Salary in India based on Location, Skills, Experience, country and more. Today softw
Read More

by Rohan Vats

Top 40 Most Common CSS Interview Questions and Answers [For Freshers & Experienced]
15248
Every industry has started the use of websites and applications to catch up with the pace of the rapidly transforming world. CSS is one of the most cr
Read More

by Rohan Vats

19 Feb 2024

Top 10 Highest Paying Programming Languages In India [2024]
95105
Programmers and Developers are among the highest-paid professionals in the world. They earn six-figure annual salary packages in countries like the US
Read More

by Rohan Vats

19 Feb 2024

Top 12 Highest Paying Online Software Courses in India [2024]
34207
The demand for innovative software products and solutions is at an all-time high, and rest assured, it will only peak higher in the coming years. One
Read More

by Rohan Vats

19 Feb 2024

23 Exciting Software Development Project Ideas & Topics for Beginners [updated 2024]
919381
Summary: In this article, you will learn the 23 Exciting Software Development Project Ideas & Topics for 2023. Take a glimpse below. Android tas
Read More

by Rohan Vats

19 Feb 2024

Must Read 50 OOPs Interview Questions & Answers For Freshers & Experienced [2024]
122372
Attending a programming interview and wondering what are all the OOP interview questions and discussions you will go through? Before attending an inte
Read More

by Rohan Vats

18 Feb 2024

25 Exciting Best Django Project Ideas & Topics For Beginners [2023]
136360
What is a Django Project? Django projects with source code are a collection of configurations and files that help with the development of website app
Read More

by Kechit Goyal

18 Feb 2024

44 Must Know Agile Methodology Interview Questions & Answers: Ultimate Guide 2024
162928
Attending an agile interview and wondering what are all the questions and discussions you will go through? Before attending an agile testing interview
Read More

by Arjun Mathur

18 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon