This “Socket Programming in Java” tutorial introduces socket programming over TCP/IP networks and shows how to write client/server applications in Java along with its examples, ServerSocket class methods, the Socket Class, and the uses of Socket testing applications. You'll learn in detail about programming on both the client and server sides of using Java sockets. So let's read the blog to find out more.
Socket programming in Java allows programs running on multiple JREs to communicate. It may be connection-oriented or connection-free. Overall, a socket is a connection-establishing mechanism between a client and a server. Socket programming is all about getting two systems to talk to each other. Typically, there are two types of network communication: User Datagram Protocol (UDP) & Transport Control Protocol (TCP).
We will present a fundamental one-way Client and Server configuration in which a Client connects and transmits messages to the server. The server displays them using a socket connection. The Java API networking package (java.net) takes care of all the low-level details required for these things to function, making network programming very simple for programmers.
Table of Content: Socket Programming in Java |
TCP stands for Transmission Control Protocol. It might also be referred to as a connection-oriented protocol. It is one of the most widely used protocols in the IP suite. It enables data packets to be sent between connected computer systems over a network. Its features include error detection and reliable communication. They are two types of sockets. They are the client socket and server socket. A client socket aids in establishing communication between the client and the server, while a server socket waits for a request from a client.
If you want to enrich your career and become a professional in Core Java, then enroll in "Core Java Training" - This course will help you to achieve excellence in this domain. |
Java is a high-level language that can be used to set up connections between a server and a client. Using socket programming, you can do this. The server creates the listener socket, and the client connects to it. For connection-oriented socket programming, the Socket class and the Server Socket class are used.
Now, let's figure out what a socket is, which is the main idea behind socket programming in Java.
Sockets are important for computer networking. These are regarded as the endpoints of the communication line. Two sockets must be created at both the server and client ends to connect two machines. The ServerSocket class of the Java computer language controls the server end of the socket, whereas the Server class controls the client end. The client must understand the characteristics of the IP address and port number in order to connect to the server.
After submitting a request, the client must wait for the server to authorize it. The server approves the request using the accept() function.
Now that you know what a Socket is in Java, let's look at how the client communicates with the server and how the server responds.
Examples of Java Socket Programming are divided into two sections.
In client-side programming, the client will wait for the server to start before it does anything. It will send the requests to the server once it is up and running. The client will then wait for a reply from the server. So, this is how clients and servers talk to each other. Now, let's learn more about what client-side programming and server-side programming are.
Follow the steps below to start a client's request:
The first step is to set up a connection to a socket. A socket connection means that the two machines know each other's location on the network (IP Address) and TCP port.
Streams are used to communicate across a socket connection for both input and output data. After establishing a connection and sending requests, the connection must be closed.
The socket connection is explicitly closed once the message has been transmitted to the server.
Now let's examine how to construct a Java program to implement a client-side socket connection.
// A Java program for a ClientSide
import java.net.*;
import java.io.*;
public class ClientProgram
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, 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);
}
}
Now, let's do some programming on the server side and then get to the output.
The server will create the required object and await a request from the client. The server will respond with the response once the client has sent the request.
The following actions must be taken in order to initiate a server-side request:
The server will create an instance of the object and wait for a client to request it. Once the client sends the request, the server will respond in kind.
To write the server-side program, you'll need to implement two sockets:
Following this, you must communicate the response to the client.
The output is sent through the socket using the getOutputStream() method.
When everything is done, it is important to close the connection by closing the socket and the input/output streams.
Now, let's look at how to write a Java program to implement a socket connection on the server side.
/ /A Java program for a Server Side
import java.net.*;
import java.io.*;
public class ServerSide
{
//initialize socket and input stream
private Socket socket = null;
private ServerSocket server = null;
private DataInputStream in = null;
// constructor with port
public Server(int port)
{
// starts server and waits for a connection
try{
server = new ServerSocket(port);
System.out.println("Server started");
System.out.println("Waiting for a client ...");
socket = server.accept();
System.out.println("Client accepted");
// takes input from the client socket
in = new DataInputStream(
new BufferedInputStream(socket.getInputStream()));
String line = "";
// reads 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);
}
}
When everything on the client and server ends has been set up, the software on the server can be run. Next, the client-side software must be executed and the request sent. The server will react immediately after the client sends the request.
In Java, this is how you need to run a socket program. You can also use a terminal window or a command prompt to run these programs. But because Eclipse's features are so advanced, you can just run both programs on a console.
Related Article: Why You Should Learn Java Programming |
A socket and socket class are essentially the most important elements in a connection-oriented protocol. Programmers can use the functions and input parameters provided by the socket class in Java to help with everything from socket creation to data transmission between sockets. Additionally, it allows for the transfer of data between the ends that is both synchronous and asynchronous.
Following are the few important methods that are present in the Socket Class:
For Socket Programming, the ServerSocket class is essential. This class carries out server socket implementation. A server socket maintains an eye for network requests to come in. Before possibly returning a result to the client, it performs an operation based on the request.
Following is the list of important methods that are present in the Socket Class:
Related Article: Classes and Objects in Java |
We can test the applications in two methods, as follows:
Using Intellij or other IDEs
Using command prompt/terminal
One endpoint of a two-way communication channel between two network-running programs is a socket. In order for the TCP layer to recognize the application that data is intended for, a socket must be bound to a port number.
Two nodes on a network can connect and communicate with one another using socket programming. While the first socket listens on a particular port at an IP address, the other socket (node) extends its hand to establish a connection with the first socket. The server creates the listener socket while the client tries connecting.
Stream Socket(SOCK_STREAM), Datagram Socket(SOCK_DGRAM), and Raw Socket(SOCK_RAW)
For client and server communication, sockets are frequently employed. The server typically resides on one machine, while the clients are located on other machines. After connecting to the server, the clients communicate with it before cutting their connection. A socket proceeds in a typical manner.
In this article, we understood the basic concept of socket programming in Java, the procedure, and the implementation with an example. We hope this article helped you to get a good understanding of it. Suggestions and feedback are always welcome.
If you are thinking of starting your career as a Java programmer, then enroll your name on the JAVA Training Course to start learning
Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:
Name | Dates | |
---|---|---|
Core Java Training | Nov 19 to Dec 04 | View Details |
Core Java Training | Nov 23 to Dec 08 | View Details |
Core Java Training | Nov 26 to Dec 11 | View Details |
Core Java Training | Nov 30 to Dec 15 | View Details |
Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .