Know All About Socket Programming In Java

Swatee Chand
Edureka
Published in
7 min readJul 12, 2019
Socket Programming in Java — Edureka

Socket programming in Java is used for communication between the applications that are running on different JRE. It can be either connection-oriented or connectionless. On the whole, a socket is a way to establish a connection between a client and a server. In this article, I will tell you all about Socket Programming.

Below topics are covered in this article:

  • What is Socket Programming in Java?
  • What is a Socket in Java?
  • Client Side Programming
  • Server Side Programming

What is Socket Programming in Java?

Socket programming is a way of connecting two nodes on a network to communicate with each other. One socket (node) listens on a particular port at an IP, while other socket reaches out to the other in order to form a connection.

The server forms the listener socket while the client reaches out to the server. Socket and Server Socket classes are used for connection-oriented socket programming.

Now let’s understand the core concept of Socket Programming i.e. a socket.

What is a Socket in Java?

A socket in Java is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.

An endpoint is a combination of an IP address and a port number. The package in the Java platform provides a class, Socket that implements one side of a two-way connection between your Java program and another program on the network. The class sits on top of a platform-dependent implementation, hiding the details of any particular system from your Java program. By using the class instead of relying on native code, your Java programs can communicate over the network in a platform-independent fashion.

Now that you know, what is Socket in Java, let’s move further and understand how does client communicates with the server and how the server responds back.

Client-Side Programming

In the case of client-side programming, the client will first wait for the server to start. Once the server is up and running, it will send the requests to the server. After that, the client will wait for the response from the server. So, this is the whole logic of client and server communication. Now let’s understand the client-side and server-side programming in detail.

In order to initiate a clients request, you need to follow the below-mentioned steps:

1. Establish a Connection

The very first step is to establish a socket connection. A socket connection implies that the two machines have information about each other’s network location (IP Address) and TCP port.

You can create a Socket with the help of a below statement:

Socket socket = new Socket(“127.0.0.1”, 5000)

  • Here, the first argument represents the IP address of Server.
  • The second argument represents the TCP Port. (It is a number that represents which application should run on a server.)

2. Communication

In order to communicate over a socket connection, streams are used for both input and output the data. After establishing a connection and sending the requests, you need to close the connection.

3. Closing the connection

The socket connection is closed explicitly once the message to the server is sent.

Now let’s see how to write a Java program to implement socket connection at the client-side.

// 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 implement server-side programming and then arrive at the output.

Server-Side Programming

Basically, the server will instantiate its object and wait for the client request. Once the client sends the request, the server will communicate back with the response.

In order to code the server-side application, you need two sockets and they are as follows:

  • A ServerSocket which waits for the client requests (when a client makes a new Socket())
  • A plain old socket for communication with the client.

After this, you need to communicate with the client with the response.

Communication

getOutputStream() method is used to send the output through the socket.

Close the Connection

It is important to close the connection by closing the socket as well as input/output streams once everything is done.

Now let’s see how to write a Java program to implement socket connection at server side.

// A Java program for a Serverside
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);
}
}

After configuring both client and server end, you can execute the server-side program first. After that, you need to run the client side program and send the request. As soon as the request is sent from the client end, the server will respond back. Below snapshot represents the same.

1. When you run the server-side script, it will start and wait for the client to get started.

2. Next, the client will get connected and inputs the request in the form of a string.

3. When the client sends the request, the server will respond back.

That’s how you need to execute a socket program in Java. You can also execute these programs on a terminal window or a command prompt. But, as Eclipse is well advanced with its features, you can simply execute both the programs on a console.

This brings us to the end of the article on Socket Programming in Java. I hope I have thrown some light on to your knowledge on Socket Programming.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Java.

1. Object Oriented Programming

2. Inheritance in Java

3. Polymorphism in Java

4. Abstraction in Java

5. Java String

6. Java Array

7. Java Collections

8. Java Threads

9. Introduction to Java Servlets

10. Servlet and JSP Tutorial

11. Exception Handling in Java

12. Advanced Java Tutorial

13. Java Interview Questions

14. Java Programs

15. Kotlin vs Java

16. Dependency Injection Using Spring Boot

17. Comparable in Java

18. Top 10 Java frameworks

19. Java Reflection API

20. Top 30 Patterns in Java

21. Core Java Cheat Sheet

22. Java Tutorial

23. Java OOP Cheat Sheet

24. Annotations in Java

25. Library Management System Project in Java

26. Trees in Java

27. Machine Learning in Java

28. Top Data Structures & Algorithms in Java

29. Java Developer Skills

30. Top 55 Servlet Interview Questions

31. Top Java Projects

32. Java Strings Cheat Sheet

33. Nested Class in Java

34. Java Collections Interview Questions and Answers

35. How to Handle Deadlock in Java?

36. Top 50 Java Collections Interview Questions You Need to Know

37. What is the concept of String Pool in Java?

38. What is the difference between C, C++, and Java?

39. Palindrome in Java- How to check a number or string?

40. Top MVC Interview Questions and Answers You Need to Know

41. Top 10 Applications of Java Programming Language

42. Deadlock in Java

43. Square and Square Root in Java

44. Typecasting in Java

45. Operators in Java and its Types

46. Destructor in Java

47. Binary Search in Java

48. MVC Architecture in Java

49. Hibernate Interview Questions And Answers

Originally published at https://www.edureka.co on July 12, 2019.

--

--