Open In App

Network Input in Java

Last Updated : 15 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, Network Input is all about sending and getting data over a network. It’s about making links, getting data from input sources, and dealing with the information we get. Java offers strong tools, like input streams and sockets. These help with these operations so communication between devices is smooth.

Prerequisites:

Before starting with network input in Java, it’s important to know some basic ideas about Java programming. This includes classes, methods, and the basics of networks too. Knowing basic input/output operations in Java and the basics of socket programming will help you understand this subject better.

Sockets

In Java, sockets give the basic structure for online connections. They help make sure things can talk to each other over a network. The Socket class bundles a device used for talking and lets two-way communication happen between client and server programs. It uses in/out streams (getInputStream() and getOutputStream()) to handle data flow.

Example of Network Input

Let’s show how to get data from a server using a socket input stream in Java:

Java




import java.io.*;
import java.net.*;
  
public class NetworkInputExample {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("hostname", portNumber);
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
  
            String data;
            while ((data = reader.readLine()) != null) {
                System.out.println("Received: " + data);
            }
  
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Explanation of the above Program:

  • Make a socket thing by giving the server’s name and port number.
  • Get the information flow from the socket and cover it with an InputStreamReader and BufferedReader. This makes reading easier.
  • Read data one line at a time from the input source until there’s no more information to get.
  • Close the socket after reading.
  • This example shows a simple way to get info from a server using the input stream of socket on the client side.

Conclusion

Knowing network input in Java is important for making strong apps that talk over networks. Using input streams and sockets lets developers send data smoothly. This helps computers talk to each other without problems. By learning these ideas, Java coders can easily make complex internet-based programs.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads