Socket Programming in Java
Last Updated :
03 Jan, 2025
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);
}
}
Outputjava.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:
- Compile both of them on two different terminals or tabs
- Run the Server program first
- Then run the Client program
- Type messages in the Client Window which will be received and shown by the Server Window simultaneously.
- Type Over to end.
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Programs - Java Programming Examples In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Java Interface An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Introduction to Java Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is platform-independent, which means we can write code once and run it anywhere using the Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications, Android
4 min read