The Wayback Machine - https://web.archive.org/web/20240901124009/https://www.geeksforgeeks.org/socket-programming-in-java/
Open In App

Socket Programming in Java

Last Updated : 17 Jan, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

This article describes a very basic one-way Client and Server setup where a Client connects, sends messages to the server and the server shows them using a socket connection. There’s a lot of low-level stuff that needs to happen for these things to work but the Java API networking package (java.net) takes care of all of that, making network programming very easy for programmers.

Client-Side Programming

Establish a Socket Connection 

To connect to another machine we need a socket connection. A socket connection means the two machines have information about each other’s network location (IP Address) and TCP port. The java.net.Socket class represents a Socket. To open a socket: 

Socket socket = new Socket(“127.0.0.1”, 5000)
  • The first argument – IP address of Server. ( 127.0.0.1  is the IP address of localhost, where code will run on the single stand-alone machine).
  • The second argument – TCP Port. (Just a number representing which application to run on a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

Communication 
To communicate over a socket connection, streams are used to both input and output the data. 

Closing the connection

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

In the program, the Client keeps reading input from a user and sends it to the server until “Over” is typed.

Java Implementation

Java




// A Java program for a Client
import java.io.*;
import java.net.*;
 
public class Client {
    // 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);
            return;
        }
        catch (IOException i) {
            System.out.println(i);
            return;
        }
 
        // 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);
    }
}


Server Programming

Establish a Socket Connection

To write a server application two sockets are needed. 

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

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

Close the Connection 
After finishing,  it is important to close the connection by closing the socket as well as input/output streams.

Java




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


Important Points 

  • Server application makes a ServerSocket on a specific port which is 5000. This starts our Server listening for client requests coming in for port 5000.
  • Then Server makes a new Socket to communicate with the client.
socket = server.accept()
  • The accept() method blocks(just sits there) until a client connects to the server.
  • Then we take input from the socket using getInputStream() method. Our Server keeps receiving messages until the Client sends “Over”.
  • After we’re done we close the connection by closing the socket and the input stream.
  • To run the Client and Server application on your machine, compile both of them. Then first run the server application and then run the Client application.

To run on Terminal or Command Prompt

Open two windows one for Server and another for Client

1. First run the Server application as,  

$ java Server

Server started 
Waiting for a client …

2. Then run the Client application on another terminal as,  

$ java Client

It will show – Connected and the server accepts the client and shows,
Client accepted

3. Then you can start typing messages in the Client window. Here is a sample input to the Client  

Hello
I made my first socket connection
Over

Which the Server simultaneously receives and shows,  

Hello
I made my first socket connection
Over
Closing connection

Notice that sending “Over” closes the connection between the Client and the Server just like said before. 

If you’re using Eclipse or likes of such-

  1. Compile both of them on two different terminals or tabs
  2. Run the Server program first
  3. Then run the Client program
  4. Type messages in the Client Window which will be received and shown by the Server Window simultaneously.
  5. Type Over to end.

 



Previous Article
Next Article

Similar Reads

Transfer the File "Client Socket to Server Socket" in Java
Prerequisites: Socket Programming in JavaFile Handling in JavaThis article describes a one-way client and Server Setup where a client connects, and sends the file to the server and the server writes the file in another location with a different name. It means we send the file using the server socket. Socket Programming in JavaSocket Programming is
4 min read
Socket Programming with Multi-threading in Python
Prerequisite : Socket Programming in Python, Multi-threading in PythonSocket Programming-> It helps us to connect a client to a server. Client is message sender and receiver and server is just a listener that works on data sent by client.What is a Thread? A thread is a light-weight process that does not require much memory overhead, they are che
3 min read
java.net.Socket Class in Java
The java.net.Socket class allows us to create socket objects that help us in implementing all fundamental socket operations. We can perform various networking operations such as sending, reading data and closing connections. Each Socket object that has been created using with java.net.Socket class has been associated exactly with 1 remote host, for
5 min read
Legacy Socket API in Java
The Java Socket API has been around for more than two decades. It has been maintained and updated over that period, but even the most well-kept code ultimately has to be upgraded to stay up with contemporary technologies. The fundamental classes that handle Socket interaction in Java 13 have been re-implemented to take advantage of the present stat
4 min read
How to Make a Server to Allow the Connection to the Socket 6123 in Java?
A socket connection means the two machines have information about each other’s network location (IP Address) and TCP port. The java.net.Socket class represents a Socket. Here, we are going to look at the approach of connecting to socket 6123. Approach: Create an object of Socket class and pass 6123 as an argument.Accept connections with accept() me
2 min read
Creating a Socket to Display Message to a Single Client in Java
This article describes the basic client-server connection where a client connects, a server sends a message to the client and the client displays the message using a socket connection. A client program sockets establish a connection with the server socket of server application then server socket connects with internal sockets in the server applicat
2 min read
How to Create a Socket at a Specific Port in Java?
A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. Socket Programming, us basically client-server programming where a socket is used as a link between them. We need to import the 'java.net package in
3 min read
Difference between Secure Socket Layer (SSL) and Secure Electronic Transaction (SET)
Secure Socket Layer (SSL): Secure Socket Layer (SSL) is the normal security technology for establishing an associate encrypted link between an internet server and a browser. This link ensures that each knowledge passed between the online server and browsers stays personal and integral. SSL is associate trade normal and is employed by numerous websi
7 min read
Socket in Computer Network
A socket is one endpoint of a two way communication link between two programs running on the network. The socket mechanism provides a means of inter-process communication (IPC) by establishing named contact points between which the communication take place. Like 'Pipe' is used to create pipes and sockets is created using 'socket' system call. The s
2 min read
Difference between Rest API and Web Socket API
In IoT, there are 2 communication APIs - REST Based Communication APIsWeb Socket Based Communication APIs Web service can either be implemented using REST principles or using Web Socket Protocol - 1. REST Based Communication API : REpresentational State Transfer (REST) is a set of architectural principles by which you can design web services and we
4 min read
Types of Socket
A network that is connected with two devices as a link to execute two-way communication on the network. It receives and sends data to the devices. The socket address is a combination of IP address and port. In the TCP/IP layer, a socket is bound as a port number which can identify whether the data is to be sent to an application or not. The transpo
3 min read
Spring Boot - Web Socket
WebSocket is used as a communication protocol that provides full-duplex communication channels over a single, long-lived connection between a client and a server. In this protocol, there are no restrictions like HTTP that for a response you have to make a request first. The server can send the message without getting any request and this can be use
10 min read
Secure Socket Layer (SSL)
Secure Socket Layer (SSL) provides security to the data that is transferred between web browser and server. SSL encrypts the link between a web server and a browser which ensures that all data passed between them remain private and free from attack. In this article, we are going to discuss SSL in detail, its protocols, the silent features of SSL, a
11 min read
Difference between RMI and Socket
This article describes techniques for Client and Server setup where a Client connects, sends messages to the server and the server shows them using a connection and vice versa. RMI and Sockets both are used to establish a connection between client and server but there are some major differences between RMI and Socket, let's look into it. but before
4 min read
Difference Between Secure Socket Layer (SSL) and Transport Layer Security (TLS)
SSL stands for Secure Socket Layer while TLS stands for Transport Layer Security. Both Secure Socket Layer and Transport Layer Security are the protocols used to provide security between web browsers and web servers. The main difference between Secure Socket Layer and Transport Layer Security is that, in SSL (Secure Socket Layer), the Message diges
4 min read
Difference between Structured Programming and Object Oriented Programming
1. Structured Programming :Structured Programming, as name suggests, is a technique that is considered as precursor to OOP and usually consists of well-structured and separated modules. In this programming, user can create its own user-defined functions as well as this methodology tries to resolve issues that are associated with unconditional trans
3 min read
Learn Programming Languages- List of 11 Popular Programming Languages
In this rapidly growing world, programming languages are also rapidly expanding, and it is very hard to determine the exact number of programming languages. It is an essential part of software development because it creates a communication bridge between humans and computers. Now, if you are a beginner who wants to learn, search the internet, you w
9 min read
Java tricks for competitive programming (for Java 8)
Although the practice is the only way that ensures increased performance in programming contests but having some tricks up your sleeve ensures an upper edge and fast debugging.1) Checking if the number is even or odd without using the % operator:Although this trick is not much better than using a % operator but is sometimes efficient (with large nu
5 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Comparison of Java with other programming languages
Java is one of the most popular and widely used programming language and platform. A platform is an environment that helps to develop and run programs written in any programming language. Java is fast, reliable and secure. From desktop to web applications, scientific supercomputers to gaming consoles, cell phones to the Internet, Java is used in ev
4 min read
What is Reactive Programming in Java?
Reactive programming is an important programming paradigm that is becoming increasingly popular in Java development. Reactive programming is based on the use of asynchronous and non-blocking data streams to handle data and events. In this article, we will explore the concept of reactive programming in Java, its use cases, and how it can benefit dev
4 min read
Functional Programming in Java with Examples
So far Java was supporting the imperative style of programming and object-oriented style of programming. The next big thing what java has been added is that Java has started supporting the functional style of programming with its Java 8 release. In this article, we will discuss functional programming in Java 8. What is functional programming? It is
9 min read
Top 7 Java Project Ideas To Enhance Programming Skills
Do you know that despite going through numerous lectures, notes, training sessions, etc., and covering all the required concepts, most of the programmers still don't get enough confidence and expertise with their programming skills? Want to know the main reason behind that…?? Okay, so it is due to the lack of Project Building i.e., you're required
7 min read
Brief Overview & Comparison of Object-Oriented Programming from C to Java
In this article, you will get the ability to think how really OOP works in Java through C. Through C, you will understand the concept of Polymorphism, Inheritance, Encapsulation, Class, Objects, etc. As you also know C language don't support OOP, but we can understand the concept behind it by defining a fine structure as a Class and Creating its Id
3 min read
What is Snippet and How to Create Java Snippets in VSCode for Competitive Programming?
The snippet refers to a small piece of re-usable source code, machine code, or text that with the help of the snippet we can use long lines code again and again in our programs. Snippets are a great tool to write programs faster. Typing speed is very important for competitive programming. Generally, there are two classes used in java for Performing
5 min read
Why Java Language is Slower Than CPP for Competitive Programming?
Choosing the appropriate language while starting competitive programming is the most important factor. Generally, we choose that language that has short syntax and executes very fast or which is familiar to us, and we know all the working patterns of that particular whether it is Java or C++. Most of the programmers use C++ for competitive programm
5 min read
Java Generics to Code Efficiently in Competitive Programming
Templates are the foundation of generic programming, which involve writing code in a way that is independent of any particular type. These powerful tools can be used for writing our code effectively. Some cool tricks that may be used in Competitive Programming are given as follows: Fast Input/Output: This uses the time advantage of BufferedReader a
9 min read
Setting up Java Competitive Programming Environment
An operating system is required to be installed on your system. here we will be discussing the setup in windows. However, you can choose any operating system. Install JDK (Java Development Kit) JDK, is a program that allows you to write Java code from the comfort of your desktop. It contains a variety of tools that are very useful for creating, run
5 min read
Java GUI Programming - Implementation of javaFx based TreeView
TreeView is one of the most important controls which implements a hierarchical view of data in a tree-like format in GUI-based Java Programming using JavaFX. “Hierarchical” means some items are placed as subordinate items to others, for example, a tree is commonly used for displaying contents of the file system in which the individual files are sub
4 min read
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and from where python being slowest among dynamic is hardly seen i
8 min read
Article Tags :
Practice Tags :