Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Java Socket Programming
3.
Socket Class
3.1.
Important Methods
4.
ServerSocket Class
4.1.
Important Methods
5.
Examples of Socket Programming
5.1.
Java Socket Programming Example (Read-Write both sides)
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Mar 27, 2024

Socket programming

Author Sanjana Yadav
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

In Java, socket programming is used to communicate across programs running on different JREs. It might be connection-oriented or non-connection-oriented. A socket, in general, is a method of establishing a connection between a client and a server.

Java Socket Programming

Sockets provide a means of communication between two machines using TCP. At its end of the conversation, a client application builds a socket and attempts to connect it to a server.

The server produces a socket object when the connection is established. Writing to and reading from the socket allows the client and server to interact.

When the connection is established, the server produces a socket object on its end of the conversation. The client and server can now exchange information by writing to and reading from the socket.

The java.net.Socket class represents a socket. The java.net.ServerSocket class gives the server program a way to listen to clients and connect with them.

Following are the steps to establish a TCP connection between two computers using sockets-

  1. The server creates a ServerSocket object, which provides the port number for communication.
  2. The server calls the accept() function of the ServerSocket class. This method waits for a client to connect to the server on the specified port before returning.
  3. After the server has been waiting, a client creates a Socket object, providing the server name and port number to connect to.
  4. The Socket class's constructor tries to connect the client to the provided server and port number. If communication is established, the client is now in possession of a Socket object that may communicate with the server.
  5. The accept() method on the server-side returns a reference to a new socket on the server connected to the client's socket.

After the connections have been established, communication can occur via I/O streams. Each socket has an OutputStream as well as an InputStream. The client's OutputStream is linked to the server's InputStream, and the server's OutputStream is linked to the client's InputStream.

Because TCP is a two-way communication protocol, data may be transferred in both directions simultaneously.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Socket Class

A socket is just a communication endpoint between machines. To construct a socket, use the Socket class.

Important Methods

Method

Description

public InputStream getInputStream() returns the InputStream attached with this socket.
public OutputStream getOutputStream() returns the OutputStream attached with this socket.
public synchronized void close() closes this socket

ServerSocket Class

A server socket may be created using the ServerSocket class. This object is used to communicate with the clients.

Important Methods

Method

Description

public Socket accept() returns the socket and establishes a connection between server and client.
public synchronized void close() closes the server socket.

Examples of Socket Programming

Creating Server:

To build the server application, we must first construct an instance of the ServerSocket class. Port number 6666 is used for communication between the client and server in this case. You can also select another port number. The accept() function sits back and waits for the client. If a client connects to the supplied port number, it returns a Socket instance.

ServerSocket newssoc=new ServerSocket(6666);  
Socket soc=newssoc.accept();//establishes a connection and waits for the client 
  

Creating Client:

To build the client application, we must first construct an instance of the Socket class. The IP address or hostname of the server and a port number must be passed here. Because our server is operating on the same machine, we're using "localhost" here.

Socket newsoc=new Socket("localhost",6666);  

Let's look at a simple Java socket programming example in which the client transmits a text and the server receives and outputs it. Also, try it on online java compiler.

Server-side:

import java.io.*;
import java.net.*;
public class server {
    public static void main(String[] args) {
        try {
            ServerSocket ssoc = new ServerSocket(6666);
            Socket soc = ssoc.accept();// establishes connection
            DataInputStream dis = new DataInputStream(soc.getInputStream());
            String str = (String) dis.readUTF();
            System.out.println("message= " + str);
            ssoc.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Client-side:

import java.io.*;
import java.net.*;
public class client {
    public static void main(String[] args) {
        try {
            Socket soc = new Socket("localhost", 6666);
            DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
            dout.writeUTF("Hello Server");
            dout.flush();
            dout.close();
            soc.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}  

To run this program, open two command prompts and run both programs simultaneously. Following the execution of the client application, a message will be shown on the server console.

Java Socket Programming Example (Read-Write both sides)

In this example, the client will first write to the server, after which the server will receive and output the text. The server will then send a message to the client, which will receive and print the text. The process continues.

Server-side:

import java.net.*;
import java.io.*;
class server {
    public static void main(String args[]) throws Exception {
        ServerSocket ssoc = new ServerSocket(3333);
        Socket soc = ssoc.accept();
        DataInputStream din = new DataInputStream(soc.getInputStream());
        DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = "", str2 = "";
        while (!str.equals("stop")) {
            str = din.readUTF();
            System.out.println("client says: " + str);
            str2 = br.readLine();
            dout.writeUTF(str2);
            dout.flush();
        }
        din.close();
        soc.close();
        ssoc.close();
    }
}

Client-side:

import java.net.*;
import java.io.*;
class client {
    public static void main(String args[]) throws Exception {
        Socket soc = new Socket("localhost", 3333);
        DataInputStream din = new DataInputStream(soc.getInputStream());
        DataOutputStream dout = new DataOutputStream(soc.getOutputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str = "", str2 = "";
        while (!str.equals("stop")) {
            str = br.readLine();
            dout.writeUTF(str);
            dout.flush();
            str2 = din.readUTF();
            System.out.println("Server says: " + str2);
        }
        dout.close();
        soc.close();
    }
}


Also see, Duck Number in Java and Hashcode Method in Java

Frequently Asked Questions

  1. What is socket programming in java?
    In Java, socket programming is used to communicate across programs running on different JREs. It might be connected-oriented or connectionless. A socket, in general, is a method of establishing a connection between a client and a server.
     
  2. Which protocol do sockets use?
    Transmission Control Protocol (TCP), Stream Control Transmission Protocol (SCTP), or Datagram Congestion Control Protocol (DCCP) connection-oriented sockets (DCCP).
     
  3. What are the advantages of socket programming?
    Allows for flexible access to files and data via a network, Pooling resources, Security, Speed, Software administration is centralized, Provides protection like sending sensitive (password-protected) information and applications via a network.
     
  4. Is socket A process?
    A socket allows two processes on the same computer or on different systems to connect with one another. A socket serves as an inter-process communicator and is regarded as the process communication's terminus. The socket communicates via a file descriptor and is commonly used in client-server applications.
     
  5. What are the Disadvantages of Java sockets?
    Socket-based communication only allows for the transmission of raw data packets between apps. Both the client and the server must provide tools to make the data values in some way.

Key Takeaways

  • Cheers if you reached here! In this blog, we learned about Socket programming in Java.
  • We have covered the Socket and the ServerSocket classes and their uses.
  • We have also seen different methods inside Socket and ServerSocket classes and their uses.
  • Further, we saw examples of socket programming in java.
     

On the other hand, learning never ceases, and there is always more to learn. So, keep learning and keep growing, ninjas!

Check out the Computer Networks to know more about computer networking.

Good luck with your preparation!

Previous article
Introduction to Java Networking
Next article
Java URL
Live masterclass