Java Networking
Java networking is used to connect two or more computing devices so that they can
exchange data and share resources over a network. It allows applications to communicate
over the internet or local networks.
Java provides built-in support for networking through the [Link] package, which includes
classes and interfaces for handling communication, sockets, URLs, and network resources.
In this chapter, we will learn about Java networking basics, protocols, terminology, important
classes, and how communication happens between client and server applications.
What is Java Networking?
Java networking is the concept of establishing communication between multiple devices
using Java programs. It enables data sharing, remote access, and distributed computing.
Java socket programming is an important part of networking, which allows applications
running on different machines to communicate with each other.
Advantage of Java Networking
The following are the advantages of using networking in Java:
It enables resource sharing between systems, such as sharing files, printers, and
applications over a network.
It supports centralized software and data management that allows data and
applications to be maintained at a single location for better control and consistency.
It allows communication between distributed applications, where programs running
on different machines can interact and exchange data seamlessly.
It helps in building client-server applications, where clients request services and
servers provide responses over a network.
Network Protocols ([Link] Package)
The [Link] package supports two main types of network protocols that are used for
communication between devices: TCP and UDP.
1. TCP (Transmission Control Protocol)
TCP is a connection-oriented protocol that establishes a connection between the sender and
receiver before data transmission begins. It provides reliable and ordered communication
which ensures that data is delivered without loss or duplication. TCP is used along with the
Internet Protocol, commonly referred to as TCP/IP, and is widely used in applications such as
web browsing, file transfer, and email services.
2. UDP (User Datagram Protocol)
UDP is a connection-less protocol that does not establish a connection before sending data.
It allows packets of data to be transmitted directly between nodes that makes it faster but
less reliable than TCP. UDP does not guarantee delivery, order, or duplication of data, and is
commonly used in applications like video streaming, online gaming, and real-time
communication.
Java Networking Terminology
The widely used Java networking terminologies are given below:
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. [Link] . It is
composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable
but slow. The example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not
reliable but fast. The example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communications.
Visit next page for Java socket programming.
[Link] package
The [Link] package can be divided into two sections:
The [Link] package provides classes and interfaces to build networking applications in
Java. It helps in handling communication, sockets, IP addresses, URLs, and other network-
related operations.
The [Link] package can be divided into two main sections:
Low-Level API
The Low-Level API deals with the basic networking components such as:
Addresses (network identifiers like IP addresses)
Sockets (bidirectional data communication between systems)
Network Interfaces (hardware-level communication support)
It is mainly used for socket programming and direct communication between client and
server.
High-Level API
The High-Level API deals with web-based resources and abstractions such as:
URI (Uniform Resource Identifier)
URL (Uniform Resource Locator)
URLConnection (communication with web resources)
Java Socket Programming
Java socket programming is used to establish communication between applications running
on different systems or different Java Runtime Environments (JREs). It enables data
exchange over a network using client-server architecture.
In this chapter, we will learn what socket programming is, how it works in Java, and the basic
components used for communication between client and server.
What is Java Socket Programming?
Java Socket Programming is a technique that allows two applications to communicate with
each other over a network. It can be implemented in two ways:
Connection-oriented communication (TCP)
Connection-less communication (UDP)
For connection-oriented communication, Java provides the following classes:
Socket: Used at the client side to establish a connection
ServerSocket: Used at the server side to listen for incoming connections
For connection-less communication, the following classes are used:
DatagramSocket
DatagramPacket
Requirements for Client-Server Communication
In socket programming, the client must know the following details of the server:
IP Address of the server
Port number on which the server is listening
How Socket Communication Works?
In a basic socket communication:
The server creates a ServerSocket and waits for client requests.
The client creates a Socket and connects to the server using IP address and port
number.
The server uses the accept() method, which blocks execution until a client connects.
Once connected, the server gets a Socket object to communicate with the client.
Both client and server can send and receive data using input and output streams.
Simple Communication Example
In a simple one-way communication:
The client sends a message to the server.
The server receives the message and displays it.
This communication is achieved using the Socket and ServerSocket classes.
Here, we are going to make one-way client and server communication. In this application,
client sends a message to the server, server reads the message and prints it. Here, two
classes are being used: Socket and ServerSocket. The Socket class is used to communicate
client and server. Through this class, we can read and write message. The ServerSocket class
is used at server-side. The accept() method of ServerSocket class blocks the console until the
client is connected. After the successful connection of client, it returns the instance of Socket
at server-side.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.
Important methods
Several important methods of socket class are as follows:
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this
socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this
socket.
3) public synchronized void close() closes this socket
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Several important methods of ServerSocket class are as follows:
Method Description
1) public Socket accept() returns the socket and establish a
connection between server and client.
2) public synchronized void close() closes the server socket.
Example of Java Socket Programming
Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here,
we are using 6666 port number for the communication between the client and server. You
may also choose any other port number. The accept() method waits for the client. If clients
connects with the given port number, it returns an instance of Socket.
1. ServerSocket ss=new ServerSocket(6666);
2. Socket s=[Link]();//establishes connection and waits for the client
Creating Client:
To create the client application, we need to create the instance of Socket class. Here, we
need to pass the IP address or hostname of the Server and a port number. Here, we are
using "localhost" because our server is running on same system.
1. Socket s=new Socket("localhost",6666);
Let's see a simple of Java socket programming where client sends a text and server receives
and prints it.
File: [Link]
1. import [Link].*;
2. import [Link].*;
3. public class MyServer {
4. public static void main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=[Link]();//establishes connection
8. DataInputStream dis=new DataInputStream([Link]());
9. String str=(String)[Link]();
10. [Link]("message= "+str);
11. [Link]();
12. }catch(Exception e){[Link](e);}
13. }
14. }
File: [Link]
1. import [Link].*;
2. import [Link].*;
3. public class MyClient {
4. public static void main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new DataOutputStream([Link]());
8. [Link]("Hello Server");
9. [Link]();
10. [Link]();
11. [Link]();
12. }catch(Exception e){[Link](e);}
13. }
14. }
To execute this program open two command prompts and execute each program at each
command prompt as displayed in the below figure.
Example of Java Socket Programming (Read-Write both side)
In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes
on.
File: [Link]
1. import [Link].*;
2. import [Link].*;
3. class MyServer{
4. public static void main(String args[])throws Exception{
5. ServerSocket ss=new ServerSocket(3333);
6. Socket s=[Link]();
7. DataInputStream din=new DataInputStream([Link]());
8. DataOutputStream dout=new DataOutputStream([Link]());
9. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
10.
11. String str="",str2="";
12. while(){
13. str=[Link]();
14. [Link]("client says: "+str);
15. str2=[Link]();
16. [Link](str2);
17. [Link]();
18. }
19. [Link]();
20. [Link]();
21. [Link]();
22. }}
File: [Link]
1. import [Link].*;
2. import [Link].*;
3. class MyClient{
4. public static void main(String args[])throws Exception{
5. Socket s=new Socket("localhost",3333);
6. DataInputStream din=new DataInputStream([Link]());
7. DataOutputStream dout=new DataOutputStream([Link]());
8. BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
9.
10. String str="",str2="";
11. while(){
12. str=[Link]();
13. [Link](str);
14. [Link]();
15. str2=[Link]();
16. [Link]("Server says: "+str2);
17. }
18.
19. [Link]();
20. [Link]();
21. }}
Java URL Class
A URL (Uniform Resource Locator) is the address used to locate resources on the Internet. In
Java, the URL class provides a simple way to work with web addresses and access their
components such as protocol, host, port, and file path. In this chapter, you will learn about
the URL class, its constructors, methods, and example.
What is URL Class in Java?
The URL class is a part of the [Link] package and is used to represent a Uniform Resource
Locator (URL). A URL points to a resource available on the Internet.
For example:
1. [Link]
Using the URL class, you can extract different parts of a URL, such as:
Protocol: Defines the communication method (e.g., http, https, ftp)
Host Name (Server Name): The domain name or IP address (e.g.,
[Link])
Port Number: Optional value; if not specified, it returns -1. For example, if we write
http//[Link]/sonoojaiswal/ , 80 is the port number.
File Name / Path: The specific resource (e.g., [Link])
Example Breakdown of a URL
For the URL:
1. [Link]
Protocol: http
Host: [Link]
Port: 80
File: [Link]
If the port number is not mentioned, Java automatically returns -1.
Java URL Class Constructors
This class has the following constructors:
1. URL(String spec)
Creates an instance of a URL from the String representation.
Here is the syntax:
1. URL url = new URL(String spec);
2. URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.
Here is the syntax:
1. URL url = new URL(String protocol, String host, int port, String file);
3. URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.
Here is the syntax:
1. URL url = new URL(String protocol, String host, int port, String file, URLStreamHandle
r handler);
4. URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.
Here is the syntax:
1. URL url = new URL(String protocol, String host, String file);
5. URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.
Here is the syntax:
1. URL url = new URL(URL context, String spec);
6. URL(URL context, String spec, URLStreamHandler handler)
Creates an instance of a URL by parsing the given spec with the specified handler within a
given context.
Here is the syntax:
1. URL url = new URL(URL context, String spec, URLStreamHandler handler);
URL Class Methods
The [Link] class provides many methods. The most important methods of the URL
class are given below.
Method Description
public String getProtocol() it returns the protocol of the URL.
public String getHost() it returns the host name of the URL.
public String getPort() it returns the Port Number of the URL.
public String getFile() it returns the file name of the URL.
public String getAuthority() it returns the authority of the URL.
public String toString() it returns the string representation of the URL.
public String getQuery() it returns the query string of the URL.
public String getDefaultPort() it returns the default port of the URL.
public URLConnection openConnection() it returns the instance of URLConnection i.e.
associated with this URL.
public boolean equals(Object obj) it compares the URL with the given object.
public Object getContent() it returns the content of the URL.
public String getRef() it returns the anchor or reference of the URL.
public URI toURI() it returns a URI of the URL.
Java URLConnection Class
The Java URLConnection class represents a communication link between the URL and the
application. It can be used to read and write data to the specified resource referred by the
URL.
In this chapter, you will learn about the URLConnection class, its features, and how it works
with web resources.
What is URLConnection Class in Java?
The URLConnection class is used to establish a connection between a Java application and a
URL resource. It allows users to interact with data available on the Internet by reading from
or writing to the resource.
It is an abstract class, and its commonly used subclasses are:
HttpURLConnection
JarURLConnection
Once a connection is established, it can be used to:
Read data from a URL
Write data to a URL
Get additional information such as content length, content type, etc.
Features of URLConnection Class
The URLConnection class provides several features to establish and manage communication
with web resources.
URLConnection is an abstract class. Its two
subclasses, HttpURLConnection and JarURLConnection. These are used to establish
the connection between a client Java program and a URL resource on the Internet.
Using the URLConnection class, a user can read from and write to any resource
referenced by a URL object.
Once a connection is established and the Java program obtains a URLConnection
object, it can be used to read, write, or retrieve additional information such as
content length, content type, etc.
Constructor of URLConnection Class
This class has only one constructor that is used to construct a URL connection to the
specified URL.
syntax:
1. protected URLConnection(URL url);