Networking (Socket Programming)

Java 14 min min read Updated: Mar 31, 2026 Advanced
Networking (Socket Programming)
Advanced Topic 7 of 14

Networking (Socket Programming)

In today’s software world, many applications need to communicate with other systems over a network. A chat application sends messages to another user, a browser fetches website data from a server, an online game exchanges live player actions, and a banking system talks to backend services. In Java, such communication is handled through network programming.

One of the most important concepts in Java networking is socket programming. Sockets allow two machines or two programs to communicate with each other over a network. Java provides built-in classes to make socket programming easier and more structured.

Key Concept: Socket programming in Java is used to establish communication between two systems over a network, usually through a client-server model.

What is Networking in Java?

Networking in Java means writing programs that can exchange data with other programs over a network.

Examples:

  • chat applications
  • client-server systems
  • online games
  • distributed systems
  • web services and APIs

Java provides networking support mainly through the:

java java.net

package.

What is a Socket?

A socket is one endpoint of a communication link between two programs running over a network. If two programs want to exchange data, each program uses a socket.

In simple terms:

  • one socket on client side
  • one socket on server side
  • both communicate using IP address and port number

What is Socket Programming?

Socket programming is the process of creating network applications that communicate through sockets.

It is commonly based on the client-server model.

  • Server waits for requests
  • Client sends requests

Real-World Example

Consider a food delivery application:

  • your mobile app is the client
  • the company’s backend server is the server
  • the app sends order data through the network
  • the server processes it and responds

Socket programming follows a similar communication flow.

Client-Server Architecture

In socket programming, communication usually happens between:

  • a server program that listens on a port
  • a client program that connects to that port

Flow

  1. Server starts and waits for connection
  2. Client connects using server IP and port
  3. Connection is established
  4. Data is exchanged
  5. Connection may be closed after communication

Important Networking Terms

IP Address

IP address identifies a machine on a network.

Example:

text 192.168.1.10 127.0.0.1

127.0.0.1 is the local loopback address used for testing on the same machine.

Port Number

A port number identifies a specific service or application on a machine.

Example:

text 8080 5000 9000

Multiple applications can run on the same machine using different ports.

Protocol

A protocol is the set of rules used for communication.

Common protocols:

  • TCP
  • UDP

TCP vs UDP

Point TCP UDP
Type Connection-oriented Connectionless
Reliability Reliable Less reliable
Order guarantee Yes No
Speed Slower Faster
Use cases chat, web apps, file transfer video streaming, gaming, voice calls

Most beginner socket programming examples in Java use TCP because it is easier and safer to understand.

Java Networking Classes

Important classes in Java socket programming include:

  • Socket
  • ServerSocket
  • InetAddress
  • DatagramSocket
  • DatagramPacket

Socket Class

The Socket class is used by the client to connect to a server.

It creates a communication endpoint with:

  • server IP address
  • server port number

ServerSocket Class

The ServerSocket class is used on the server side. It listens for client connection requests on a specific port.

Once a client connects, the server accepts the connection and gets a Socket object for communication.

Basic TCP Server Example

Let us first write a simple server.

java import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(5000); System.out.println("Server started. Waiting for client..."); Socket socket = serverSocket.accept(); System.out.println("Client connected"); BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); String message = br.readLine(); System.out.println("Client says: " + message); socket.close(); serverSocket.close(); } catch (Exception e) { e.printStackTrace(); } } }

Explanation

  • ServerSocket(5000) starts server on port 5000
  • accept() waits for a client connection
  • getInputStream() reads incoming data
  • BufferedReader reads the client message line by line

Basic TCP Client Example

Now let us write the client program.

java import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { try { Socket socket = new Socket("127.0.0.1", 5000); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); pw.println("Hello Server"); socket.close(); } catch (Exception e) { e.printStackTrace(); } } }

Explanation

  • Socket("127.0.0.1", 5000) connects to local server on port 5000
  • getOutputStream() sends data to server
  • PrintWriter writes a text message

How to Run the Client-Server Program

  1. Compile both files
  2. Run the server first
  3. Run the client
  4. Server receives and prints the message

Expected Server Output

text Server started. Waiting for client... Client connected Client says: Hello Server

Two-Way Communication

In the previous example, only the client sends data. In real applications, both client and server usually exchange messages.

Server with Reply

java import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(5000); System.out.println("Server started..."); Socket socket = serverSocket.accept(); BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); String msg = br.readLine(); System.out.println("Client says: " + msg); pw.println("Hello Client"); socket.close(); serverSocket.close(); } catch (Exception e) { e.printStackTrace(); } } }

Client Receiving Reply

java import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { try { Socket socket = new Socket("127.0.0.1", 5000); BufferedReader br = new BufferedReader( new InputStreamReader(socket.getInputStream()) ); PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); pw.println("Hello Server"); String reply = br.readLine(); System.out.println("Server says: " + reply); socket.close(); } catch (Exception e) { e.printStackTrace(); } } }

InetAddress Class

The InetAddress class represents an IP address and provides methods related to host names and addresses.

Example

java import java.net.*; public class Main { public static void main(String[] args) throws Exception { InetAddress ip = InetAddress.getByName("localhost"); System.out.println(ip.getHostName()); System.out.println(ip.getHostAddress()); } }

This helps identify host-related information in Java networking.

Socket Streams

Every socket provides two important streams:

  • getInputStream() → for receiving data
  • getOutputStream() → for sending data

These streams are often wrapped in:

  • BufferedReader
  • PrintWriter
  • DataInputStream
  • DataOutputStream

Using DataInputStream and DataOutputStream

These classes help send primitive data types over sockets.

Example

java DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeInt(100); DataInputStream dis = new DataInputStream(socket.getInputStream()); int value = dis.readInt();

They are useful when communication is not plain text only.

Multithreaded Server Concept

A basic server handles one client at a time. But real-world servers often need to handle many clients simultaneously. This is done using multithreading.

The server accepts each client and starts a separate thread for that client.

Simple Concept

  1. Server waits for connection
  2. When client connects, create a handler thread
  3. That thread communicates with the client
  4. Main server continues listening for more clients

This is the base idea behind chat servers and many backend services.

UDP in Java

Java also supports UDP communication using:

  • DatagramSocket
  • DatagramPacket

UDP is faster but does not guarantee delivery or order.

Simple UDP Example Idea

In UDP:

  • server does not create a permanent connection
  • client sends packets directly
  • messages may arrive late, out of order, or be lost

For beginners, TCP socket programming is usually learned first.

Common Exceptions in Socket Programming

  • UnknownHostException
  • IOException
  • SocketException
  • BindException

UnknownHostException

Happens when the host name cannot be resolved.

BindException

Happens when the port is already in use.

IOException

General input-output exception during network communication.

Real-World Uses of Socket Programming

  • chat applications
  • online multiplayer games
  • remote command systems
  • real-time notifications
  • server-client desktop applications
  • distributed applications

Best Practices in Socket Programming

  • always close sockets and streams properly
  • use try-with-resources when possible
  • handle exceptions carefully
  • use multithreading for multiple clients
  • choose TCP or UDP based on use case
  • validate input received from network sources

Common Mistakes

  • running client before server is active
  • forgetting to close sockets
  • using wrong IP or port number
  • confusing run() and start() when building multithreaded servers
  • assuming message delivery is guaranteed in UDP

Interview-Oriented Points

  • Socket programming is based on client-server communication
  • Socket is used on client side
  • ServerSocket is used on server side
  • TCP is connection-oriented and reliable
  • UDP is connectionless and faster but less reliable
  • accept() waits for a client connection
  • getInputStream() and getOutputStream() are used for communication
  • Real servers often use multithreading to support multiple clients

Conclusion

Networking and socket programming are important parts of Java because they allow programs to communicate over a network. This forms the foundation of many modern applications such as chat systems, real-time applications, and distributed software.

Understanding sockets, client-server architecture, TCP communication, and Java networking classes gives a strong foundation for building practical network-based Java applications.

Quick Summary: Socket programming in Java allows client and server programs to communicate over a network using classes like Socket and ServerSocket, usually through a TCP-based client-server model.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators