Skip to main content

Introduction to Java Networking

Introduction to Java Networking

Java Networking is a concept of connecting two or more computing devices together so that they can share resources. Java provides a collection of classes and interfaces that help us to perform tasks related to networking such as establishing a connection, data communication, etc.

Understanding the Basics

Before diving into Java Networking, let's understand some basic terms:

  • IP Address: It is a unique number assigned to a node of a network, e.g., 192.168.0.1. It is used to identify a device on the network.
  • Port Number: The port number is used to uniquely identify different applications. It acts as a communication endpoint between applications.
  • Socket: A socket is an endpoint of a two-way communication link between two programs running on the network. It is a combination of IP address and port number.

Networking Classes in Java

Java provides two types of classes for networking support:

  1. java.net.Socket class: The Socket class can be used to create a socket and connect it to a specific address and port.
  2. java.net.ServerSocket class: The ServerSocket class is used to create servers that listen for either local or remote client programs to connect to them on published ports.

Java Networking Programming

Java networking programming involves two main tasks:

  1. Writing the Server Application: The server is a program that uses a socket to bind to a specific port, listens for clients to connect to it, and then sends or receives data.
import java.io.*;  
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept(); //establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
  1. Writing the Client Application: The client is a program that can request a connection to the server on a specific port, and then it can send or receive data.
import java.io.*;  
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

Conclusion

Java networking is a broad and powerful concept that allows us to create distributed applications. Java provides a rich set of API for networking programming from simple to complex tasks. With this basic understanding of Java Networking, you can now delve into more complex topics like UDP, TCP, URL, etc. Remember, practice is essential to get a good hold on any concept.