Home  >  Blog  >   Java

Socket Programming in Java - What is TCP

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.

Rating: 4.6
  
 
1399
  1. Share:
Java Articles

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

What Is TCP?

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.

TCP

What is Java Socket Programming?

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.

What is 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.

Socket Programming in Java

Example of Java Socket Programming

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.

  • Client-Side Socket Program
  • Server-Side Socket Program

Java Socket Programming

Client-Side Socket Programming

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:

1. Establish a Connection

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.

2. Communication

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.

3. Closing the connection

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.

Server-Side Socket Programming

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:

1. Establish a Connection

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:

  1. A ServerSocket that listens for incoming requests from clients (through new Socket() calls).
  2. A simple TCP/IP-based socket for exchanging data with the user.

Following this, you must communicate the response to the client.

2. Communication

The output is sent through the socket using the getOutputStream() method.

3. Close the Connection

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

Socket Class

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:

  • getLocalPort()
  • bind()
  • isClosed()
  • isConnected()
  • getInputStream()
  • gePort()
  • getOutputStream()
  • close()

ServerSocket Class Methods

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:

  • accept()
  • channel()
  • isBound()
  • isClosed()
  • bind()
  • close()
Related Article: Classes and Objects in Java

Testing the applications

We can test the applications in two methods, as follows:

Using Intellij or other IDEs

  • Compile the two applications.
  • Execute the server application before the client application.
  • Input messages in the client window will be received and shown in the server window.
  • To leave, enter BYE.

Using command prompt/terminal

  • Create a new folder named project (the name of your package).
  • Server.java and Client.java should be placed in the project folder.
  • Launch a command prompt and navigate to the root directory.
  • Execute javac project\Server.java and then java project. Server.
  • Utilize the same process as the Server software to execute the client program.
  • Then, you can type messages in the client's window.

MindMajix Youtube Channel

Socket Programming in Java FAQs

1. What is a socket in Java?

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.

2. What is Java socket programming?

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.

3. What are the three types of socket in Java?

Stream Socket(SOCK_STREAM), Datagram Socket(SOCK_DGRAM), and Raw Socket(SOCK_RAW)

4. Where is the socket used?

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.

5. How do I create a server socket in Java?

  • Create a socket using the socket() function.
  • Using the bind() system function, bind a socket to an address.
  • The listen() system method listens for connections.
  • accept() is a system call that accepts a connection.
  • Now, send and receive data

Conclusion

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

Join our newsletter
inbox

Stay updated with our newsletter, packed with Tutorials, Interview Questions, How-to's, Tips & Tricks, Latest Trends & Updates, and more ➤ Straight to your inbox!

Course Schedule
NameDates
Core Java TrainingApr 20 to May 05View Details
Core Java TrainingApr 23 to May 08View Details
Core Java TrainingApr 27 to May 12View Details
Core Java TrainingApr 30 to May 15View Details
Last updated: 13 Apr 2023
About Author

 

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 .

read more
Recommended Courses

1 / 15