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:
Socket Programming in Java
Next article icon

Socket Programming in Java

Last Updated : 03 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 server shows them using a socket connection. There is a lot of low-level stuff that needs to happen for these things to work but the Java API networking package (java.net) takes care of all of that, making network programming very easy for programmers.

Note: A "socket" is an endpoint for sending and receiving data across a network.

Client-Side Programming

1. Establish a Socket Connection

To connect to another machine we need a socket connection. A socket connection means both machines know each other’s IP address and TCP port. The java.net.Socket class is used to create a socket.

Socket socket = new Socket(“127.0.0.1”, 5000)

  • The first argument: The IP address of Server i.e. 127.0.0.1  is the IP address of localhost, where code will run on the single stand-alone machine.
  • The second argument: The TCP Port number (Just a number representing which application to run on a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

2. Communication 

To exchange data over a socket connection, streams are used for input and output:

  • Input Stream: Reads data coming from the socket.
  • Output Stream: Sends data through the socket.

Example to access these streams:

// to read data

InputStream input = socket.getInputStream();

// to send data

OutputStream output = socket.getOutputStream();

3. Closing the Connection

The socket connection is closed explicitly once the message to the server is sent.

Example: Here, in the below program the Client keeps reading input from a user and sends it to the server until “Over” is typed.

Java
// Demonstrating Client-side Programming import java.io.*; import java.net.*;  public class Client {        // Initialize socket and input/output streams     private Socket s = null;     private DataInputStream in = null;     private DataOutputStream out = null;      // Constructor to put IP address and port     public Client(String addr, int port)     {         // Establish a connection         try {             s = new Socket(addr, port);             System.out.println("Connected");              // Takes input from terminal             in = new DataInputStream(System.in);              // Sends output to the socket             out = new DataOutputStream(s.getOutputStream());         }         catch (UnknownHostException u) {             System.out.println(u);             return;         }         catch (IOException i) {             System.out.println(i);             return;         }          // String to read message from input         String m = "";          // Keep reading until "Over" is input         while (!m.equals("Over")) {             try {                 m = in.readLine();                 out.writeUTF(m);             }             catch (IOException i) {                 System.out.println(i);             }         }          // Close the connection         try {             in.close();             out.close();             s.close();         }         catch (IOException i) {             System.out.println(i);         }     }      public static void main(String[] args) {         Client c = new Client("127.0.0.1", 5000);     } } 

Output
java.net.ConnectException: Connection refused (Connection refused) 

Explanation: In the above example, we have created a client program that establishes a socket connection to a server using an IP address and port, enabling data exchange. The client reads messages from the user and sends them to the server until the message "Over" is entered, after which the connection is closed.

Server-Side Programming

1. Establish a Socket Connection

To create a server application two sockets are needed. 

  • ServerSocket: This socket waits for incoming client requests. It listens for connections on a specific port.
  • Socket: Once a connection is established, the server uses this socket to communicate with the client.

2. Communication

  • Once the connection is established, you can send and receive data through the socket using streams.
  • The getOutputStream() method is used to send data to the client.

3. Close the Connection 

Once communication is finished, it's important to close the socket and the input/output streams to free up resources.

Example: The below Java program demonstrate the server-side programming

Java
// Demonstrating Server-side Programming import java.net.*; import java.io.*;  public class Server {        // Initialize socket and input stream     private Socket s = null;     private ServerSocket ss = null;     private DataInputStream in = null;      // Constructor with port     public Server(int port) {                // Starts server and waits for a connection         try         {             ss = new ServerSocket(port);             System.out.println("Server started");              System.out.println("Waiting for a client ...");              s = ss.accept();             System.out.println("Client accepted");              // Takes input from the client socket             in = new DataInputStream(                 new BufferedInputStream(s.getInputStream()));              String m = "";              // Reads message from client until "Over" is sent             while (!m.equals("Over"))             {                 try                 {                     m = in.readUTF();                     System.out.println(m);                  }                 catch(IOException i)                 {                     System.out.println(i);                 }             }             System.out.println("Closing connection");              // Close connection             s.close();             in.close();         }         catch(IOException i)         {             System.out.println(i);         }     }      public static void main(String args[])     {         Server s = new Server(5000);     } } 

Explanation: In the above example, we have implemented a server that listens on a specific port, accepts a client connection, and reads messages sent by the client. The server displays the messages until "Over" is received, after which it closes the connection and terminates.

Important Points:

  • Server application makes a ServerSocket on a specific port which is 5000. This starts our Server listening for client requests coming in for port 5000.
  • Then Server makes a new Socket to communicate with the client.

socket = server.accept()

  • The accept() method blocks(just sits there) until a client connects to the server.
  • Then we take input from the socket using getInputStream() method. Our Server keeps receiving messages until the Client sends “Over”.
  • After we're done we close the connection by closing the socket and the input stream.
  • To run the Client and Server application on your machine, compile both of them. Then first run the server application and then run the Client application.

Run the Application

Open two windows one for Server and another for Client.

1. Run the Server

First run the Server application as:

$ java Server

Output:

Server started 
Waiting for a client ...

2. Run the Client

Then run the Client application on another terminal as

$ java Client

Output:

Connected

3. Exchange Messages

  • Type messages in the Client window.
  • Messages will appear in the Server window.
  • Type "Over" to close the connection.

Here is a sample interaction,

Client:

Hello

I made my first socket connection

Over

Server:  

Hello

I made my first socket connection

Over

Closing connection

Notice that sending “Over” closes the connection between the Client and the Server just like said before. 

Note : If you're using Eclipse or likes of such:

  1. Compile both of them on two different terminals or tabs
  2. Run the Server program first
  3. Then run the Client program
  4. Type messages in the Client Window which will be received and shown by the Server Window simultaneously.
  5. Type Over to end.

Next Article
Socket Programming in Java

S

Souradeep Barua
Improve
Article Tags :
  • Java
  • Computer Networks
  • Socket-programming
Practice Tags :
  • Java

Similar Reads

    Socket Programming in C
    Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket(node) listens on a particular port at an IP, while the other socket reaches out to the other to form a connection. The server forms the listener socket while the client reaches out to the serv
    8 min read
    Socket Programming in C++
    In C++, socket programming refers to the method of communication between two sockets on the network using a C++ program. We use the socket API to create a connection between the two programs running on the network, one of which receives the data by listening to the particular address port, and the o
    5 min read
    Introducing Threads in Socket Programming in Java
    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 conne
    7 min read
    Legacy Socket API in Java
    The Java Socket API has been around for more than two decades. It has been maintained and updated over that period, but even the most well-kept code ultimately has to be upgraded to stay up with contemporary technologies. The fundamental classes that handle Socket interaction in Java 13 have been re
    4 min read
    java.net.Socket Class in Java
    The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class h
    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