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 Tutorials

View All

Suggested Blogs

Scrum Master Salary in India: For Freshers & Experienced [2023]
900287
Wondering what is the range of Scrum Master salary in India? Have you ever watched a game of rugby? Whether your answer is a yes or a no, you might h
Read More

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers & Experienced [2024]
904957
A Software Development Engineer (SDE) is responsible for creating cross-platform applications and software systems, applying the principles of compute
Read More

by Rohan Vats

05 Mar 2024

System Calls in OS: Different types explained
5018
Ever wondered how your computer knows to save a file or display a webpage when you click a button? All thanks to system calls – the secret messengers
Read More

by Prateek Singh

29 Feb 2024

Marquee Tag & Attributes in HTML: Features, Uses, Examples
5125
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5046
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5108
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5049
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions & Answers (Freshers & Experienced)
5122
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

10 Best Software Engineering Colleges (India and Global) 2024
5572
Software Engineering is developing, designing, examining, and preserving software. It is a structured and trained approach through which you can devel
Read More

by venkatesh Rajanala

28 Feb 2024

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