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.
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.
- Let the Server program start running.
$ java Server
- 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.
- 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
Why Learn to Code? How Learn to Code? | How to Install Specific Version of NPM Package? | Types of Inheritance in C++ What Should You Know? |
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.
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.