0% found this document useful (0 votes)
4 views38 pages

4.java Networking

This lecture covers the fundamentals of Java networking, focusing on socket programming for client-server communication. Key concepts include IP addresses, port numbers, communication protocols (TCP and UDP), and the java.net package classes such as Socket and ServerSocket. The document also provides sample code for establishing connections and handling input/output streams in a client-server application.

Uploaded by

Muntasir Mamun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views38 pages

4.java Networking

This lecture covers the fundamentals of Java networking, focusing on socket programming for client-server communication. Key concepts include IP addresses, port numbers, communication protocols (TCP and UDP), and the java.net package classes such as Socket and ServerSocket. The document also provides sample code for establishing connections and handling input/output streams in a client-server application.

Uploaded by

Muntasir Mamun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Lecture 4

“JAVA Networking”

Course Name: Object Oriented Design and Programming-II


Course Code: ICE-2101

Course Instructor
Nusrat Tasnim
Lecturer
Department of Information and Communication Technology (ICT)
Lesson Objective
1. To learn about the basics of networking as well as socket programming.

Lesson Outcome
At the end of the lesson you will be able to-
1.Apply socket programming in order to establish client server communication.
Networking Basics

Networking, also known as computer networking refers to the practice of exchanging data between
nodes over a shared medium in an information system.

The term network programming refers to writing programs that execute across multiple devices
(computers), in which the devices are all connected to each other using a network.

The java.net package contains a collection of classes and interfaces that provide the low-level
communication details, allowing you to write programs that focus on solving the problem at hand.
Java Networking Terminology
IP Address
An IP address is a unique address that distinguishes a device on the internet or a local network. IP
stands for “Internet Protocol.” It comprises a set of rules governing the format of data sent via the
internet or local network. IP Address is referred to as a logical address that can be modified. It is
composed of octets. The range of each octet varies from 0 to 255. Range of the IP Address – 0.0.0.0
to 255.255.255.255

•For Example – 192.168.0.1

Versions:
•IPv4: 32-bit addressing, organized as four 8-bit values (e.g., 192.168.0.1)
•IPv6: 128-bit addressing, organized as eight 16-bit chunks (e.g., 2001:0db8:85a3::8a2e:0370:7334)

Java handles both IPv4 and IPv6.


Java Networking Terminology (Cont…)
Port Number
A port number is a method to recognize a particular process connecting internet or other network
information when it reaches a server. The port number is used to identify different applications uniquely.
The port number is correlated with the IP address for transmission and communication among two
applications. There are 65,535 port numbers.

Here are some common port numbers:


•80 – HTTP (web traffic)
•443 – HTTPS (secure web traffic)
•21 – FTP (file transfer)
•25 – SMTP (email sending)
•53 – DNS (domain name system)

In summary, IP addresses identify devices, while port numbers identify specific services running on
those devices. Together, they allow data to reach the right destination and application over the internet.
Communication Protocols

Communication protocols are essential for enabling devices to exchange data reliably across networks.
The java.net package provides support for the two common network protocols TCP and UDP:

TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two
applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. It is a connection
oriented protocol for communications that helps in the exchange of messages between different devices over
a network. TCP is used for reliable stream-based I/O across the network.

UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be
transmitted between applications. UDP supports a simpler, hence faster, point-to-point datagram-oriented model.
Used for simple request-response communication when the size of data is less and hence there is lesser concern
about flow and error control.
Java Networking Classes

The java.net package of the Java programming language includes various classes that provide an
easy-to-use means to access network resources. Here are the description of most common classes
among all of the classes of java.net package [2].

InetAddress – The InetAddress class is used to provide methods to get the IP address of any
hostname. An IP address is expressed by a 32-bit or 128-bit unsigned number. InetAddress can handle
both IPv4 and IPv6 addresses.

Socket – The Socket class is used to create socket objects that help the users in implementing all
fundamental socket operations. The users can implement various networking actions such as sending,
reading data, and closing connections. Each Socket object built using java.net.Socket class has been
connected exactly with 1 remote host; for connecting to another host, a user must create a new socket
object.
Java Networking Classes

Server Socket – The ServerSocket class is used for implementing system-independent implementation
of the server-side of a client/server Socket Connection. The constructor for ServerSocket class throws
an exception if it can’t listen on the specified port. For example – it will throw an exception if the port
is already being used.

URL – The URL class in Java is the entry point to any available sources on the internet. A Class URL
describes a Uniform Resource Locator, which is a signal to a “resource” on the World Wide Web. A
source can denote a simple file or directory, or it can indicate a more difficult object, such as a query to
a database or a search engine.

URLConnection – The URLConnection class in Java is an abstract class describing a connection of a


resource as defined by a similar URL. The URLConnection class is used for assisting two distinct yet
interrelated purposes. Firstly it provides control on interaction with a server(especially an HTTP server)
than a URL class. Furthermore, with a URLConnection, a user can verify the header transferred by the
server and can react consequently. A user can also configure header fields used in client requests using
URLConnection.
InetAddress Class
InetAddress is a class in the java.net package used to represent an IP address (either IPv4 or IPv6). It
can be used to:

•Get IP address of a host


•Get hostname from an IP address
•Get local IP address

Factory Methods of InetAddress Class:


The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one
of the available factory methods.

Method Description
getByName(String host) Returns the IP address of the given
hostname (e.g., "google.com").
Factory Methods of InetAddress Class:

Method Description

getAllByName(String host) Returns all IP addresses associated with the given


hostname.

getByAddress(byte[] addr) Returns an InetAddress object created from the raw


IP address (byte array).

getByAddress(String host, byte[] Similar to above, but associates a hostname with the
addr) IP address.

getLocalHost() Returns the local host address of the machine where


the program is running.

Note: All factory methods throw UnknownHostException if the host cannot be resolved .
Sample Code
public class JavaApplication20 {
public static void main(String[] args) {
try {
// Local host address
InetAddress localHost = InetAddress.getLocalHost();
System.out.println("Local Host Name: " + localHost.getHostName());
System.out.println("Local IP Address: " + localHost.getHostAddress());
// IP address of a remote host (e.g., google.com)
InetAddress google = InetAddress.getByName("google.com");
System.out.println("Google Host Name: " + google.getHostName());
System.out.println("Google IP Address: " + google.getHostAddress());
// All IP addresses for a domain
InetAddress[] addresses = InetAddress.getAllByName("google.com");
for (InetAddress addr : addresses) {
System.out.println("One of Google's IPs: " + addr.getHostAddress());}
} catch (UnknownHostException e) {
System.out.println("Host not found: " + e.getMessage());}}}
Sample Code Output

Local Host Name: DESKTOP-VPHE2A1


Local IP Address: 192.168.142.226
Google Host Name: google.com
Google IP Address: 142.250.207.238
One of Google's IPs: 142.250.207.238
Socket Programming
Socket Programming

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. The java.net package in the Java development environment provides a class--Socket--that
represents one end of a two-way connection between your Java program and another program on the
network. There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients.

The ServerSocket class is designed to be a “listener,” which waits for clients to connect before
doing anything. Thus, ServerSocket is for servers. The Socket class is for clients. It is designed to
connect to server sockets and initiate protocol exchanges.

The client in socket programming must know two information:


1) IP Address of Server, and
2) Port number.
Socket Programming (Cont…)

Sockets provide the communication mechanism between two computers using TCP. A client program
creates a socket on its end of the communication and attempts to connect that socket to a server. When
the connection is made, the server creates a socket object on its end of the communication. The client
and server can now communicate by writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism
for the server program to listen for clients and establish connections with them.

The following steps occur when establishing a TCP connection between two computers using sockets:

Step 1: The server instantiates a ServerSocket object, denoting which port number communication is to
occur on.

Step 2: The server invokes the accept() method of the ServerSocket class. This method waits until a
client connects to the server on the given port.
Socket Programming (Cont…)

Step 3: After the server is waiting, a client instantiates a Socket object, specifying the server name and
port number to connect to.

Step 4: The constructor of the Socket class attempts to connect the client to the specified server and port
number. If communication is established, the client now has a Socket object capable of communicating
with the server.

Step 5: On the server side, the accept() method returns a reference to a new socket on the server that is
connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket has both
an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream,
and the client's InputStream is connected to the server's OutputStream.
Socket Programming (Cont…)

TCP is a two way communication protocol, so data can be sent across both streams at the same time.
There are following useful classes providing complete set of methods to implement sockets.

The creation of a Socket object implicitly establishes a connection between the client and server.
There are no methods or constructors that explicitly expose the details of establishing that connection.
Here are two constructors used to create client sockets:

Constructors Description

Socket (String hostName, int port) throws Creates a socket connected to the named host and
UnknownHostException, IOException port.

Socket(InetAddress address, int port) throws Creates a socket using a pre existing InetAddress
IOException object and port.
Socket Programming (Cont…)
Socket defines several instance methods. For example, a Socket can be examined at any time for the
address and port information associated with it, by use of the following methods:

Methods Description
InetAddress getInetAddress() Returns the InetAddress associated with the
Socket object. It returns null if the socket is
not connected.
int getPort() Returns the remote port to which the
invoking Socket object is connected. It
returns 0 if the socket is not connected.
int getLocalPort() Returns the local port to which the invoking
Socket object is bound. It returns -1 if the
socket is not bound.
Socket Programming (Cont…)
You can gain access to the input and output streams associated with a Socket by use of the
getInputStream( ) and getOuptutStream( ) methods, as shown here. Each can throw an
IOException if the socket has been invalidated by a loss of connection.

Methods Description

InputStream getInputStream() throws Returns the InputStream associated with


IOException the invoking socket.
OutputStream getOutputStream() throws Returns the OutputStream associated with
IOException the invoking socket.
How to open a socket?
Opening a socket

If you are programming a client, then you would open a socket like this:

try {
// Connect to server at localhost on port 5000
Socket socket = new Socket("localhost", 5000);
System.out.println("Connected to server!");

} catch (IOException e) {
e.printStackTrace();
}
Opening a socket (Cont…)
If you are programming a server, then you would open a socket like this:

try {
// Create a ServerSocket on port 5000
ServerSocket serverSocket = new ServerSocket(5000);
System.out.println("Server is waiting for client...");

} catch (IOException e) {
e.printStackTrace();}
How to create an input stream?
Creating an InputStream

On the client side, you can use the DataInputStream class to create an input stream to receive response
from the server:

try {
Socket socket = new Socket("localhost", 5000);
// Creating DataInputStream to send data to server
DataInputStream dos = new DataInputStream(socket.getInputStream());

} catch (IOException e) {
e.printStackTrace();
}
Creating an InputStream (Cont…)

On the server side, you can use DataInputStream to receive input from the client:
try {
ServerSocket serverSocket = new ServerSocket(5000);

// Creating DataInputStream to send data to server


DataInputStream dos = new DataInputStream(serverSocket.getInputStream());

} catch (IOException e) {
e.printStackTrace();
}
How to create an output stream?
Creating an OutputStream
On the client side, you can create an output stream to send information to the server socket using the class
PrintStream or DataOutputStream of java.io:

PrintStream output;
try {
output = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}

Also, you may want to use the DataOutputStream:


DataOutputStream output;
try {
output = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
Creating an OutputStream (Cont…)

On the server side, you can also create an output stream to send information to the client socket using
the class PrintStream or DataOutputStream of java.io:

PrintStream output;
try {
output = new PrintStream(serverSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}

Also, you may want to use the DataOutputStream:


DataOutputStream output;
try {
output = new DataOutputStream(serverSocket.getOutputStream());
} catch (IOException e) {
System.out.println(e);
}
How to close sockets?
Closing Sockets

Properly closing sockets in Java is important to free up system resources and avoid memory leaks or
connection issues. Close() method is used to close the sockets. You should always close:

1.The socket itself (client or accepted socket on the server)


2.Any input/output streams you used
3.The server socket (on server side)

// CLOSE RESOURCES
dis.close(); // 1. Close the stream
socket.close(); // 2. Close the accepted socket
serverSocket.close(); // 3. Close the server socket
Example of Java Socket Programming
Problem Statement:
Objective: Create a client-server application where the client sends a request to the server, and the server
responds with a greeting message.

Requirements:
1.Server:
1. Waits for incoming connections from the client.
2. Upon receiving a connection, it sends a greeting message (e.g., "Hello, Client!") back to the client.
3. After sending the greeting, the server closes the connection.
2.Client:
1. Connects to the server using its IP address and port number.
2. Waits for the server to respond.
3. Displays the greeting message sent by the server.
4. Closes the connection once the message is received.
Solution

public class ServerSide{


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(1234);
System.out.println("Server is waiting for client connection...");
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected!");
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
out.println("Hello, Client! Welcome to the server!");
out.close();
clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}}}
Solution

public class ClientSide {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String greetingMessage = in.readLine();
System.out.println("Server says: " + greetingMessage);
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}}}
Output

ServerSide
Server is waiting for client connection...
Client connected!

ClientSide
Server says: Hello, Client! Welcome to the server!
Task to solve by yourself

Objective: Implement a client-server application using Java Sockets where the client sends a name to the
server, and the server responds with a personalized greeting.
Requirements:
1.Server:
•The server should accept incoming connections from the client.
•The server should read the client's name from the input and respond with a greeting message like
"Hello, [name]! Welcome to the server!"
2.Client:
•The client should connect to the server and send its name as a message.
•The client should then display the personalized greeting message received from the server.
References

1. https://www.geeksforgeeks.org/java-networking/
2. https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/net/package-summary.html
Thank You

You might also like