0% found this document useful (0 votes)
95 views13 pages

Unit 4 - Networking Basics

Uploaded by

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

Unit 4 - Networking Basics

Uploaded by

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

V2V Classes Advanced Java Programming

Unit 4 : Networking Basics

Java Networking is a concept of connecting two or more computing devices together so that we
can share resources.

Java socket programming provides a facility to share data between different computing devices.

Advantage of Java Networking


● Sharing resources
● Centralized software management

The java.net package supports two protocols,

● TCP: Transmission Control Protocol provides reliable communication between the sender
and receiver. TCP is used along with the Internet Protocol referred to as TCP/IP.
● UDP: User Datagram Protocol provides a connection-less protocol service by allowing
packet of data to be transferred along two or more nodes

Java Networking Terminology


1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . 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:
TCP
FTP
Telnet
SMTP
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.

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

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.

java.net package
The java.net package can be divided into two sections:
● A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers,
Sockets i.e. bidirectional data communication mechanism and Interfaces i.e. network
interfaces.
● A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to the
resource pointed by URLs.
The java.net package provides many classes to deal with networking applications in Java.

Client-Server Model
The client-server model is a network architecture where a client requests information or services
from a server, which then responds to the request.

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

Reserved Sockets
Once connected, a higher-level protocol ensues, which is dependent on which port we are using.
TCP/IP reserves the lower 1,024 ports for specific protocols. Many of these will seem familiar to
us if we have spent any time surfing the Internet. Port number 21 is for FTP, 23 is for Telnet, 25
is for e- mail, 79 is for finger, 80 is for HTTP, 119 is for net-news and the list goes on. It is up to
each protocol to determine how a client should interact with the port.

Daytime
Full Name: Daytime Protocol
Use: Provides an ASCII representation of the current time on the server.
Port No: 13 (TCP/UDP)

FTP Data
Full Name: File Transfer Protocol Data
Use: Used to transfer files.
Port No: 20 (TCP)

FTP
Full Name: File Transfer Protocol
Use: Used to send FTP commands like put and get.
Port No: 21 (TCP)

SSH
Full Name: Secure Shell
Use: Used for encrypted, remote logins.
Port No: 22 (TCP)

Telnet
Full Name: Telnet Protocol
Use: Used for interactive, remote command-line sessions.
Port No: 23 (TCP)

SMTP
Full Name: Simple Mail Transfer Protocol
Use: Used to send email between machines.
Port No: 25 (TCP)

Time
Full Name: Time Protocol
Use: Returns the number of seconds elapsed since midnight, January 1, 1900.

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

Port No: 37 (TCP/UDP)

Whois
Full Name: Whois Protocol
Use: A simple directory service for Internet network administrators.
Port No: 43 (TCP)

Finger
Full Name: Finger Protocol
Use: Returns information about a user or users on the local system.
Port No: 79 (TCP)

HTTP
Full Name: Hypertext Transfer Protocol
Use: The underlying protocol of the World Wide Web.
Port No: 80 (TCP)

POP3
Full Name: Post Office Protocol Version 3
Use: Transfers accumulated email from the host to sporadically connected clients.
Port No: 110 (TCP)

NNTP
Full Name: Network News Transfer Protocol
Use: Usenet news transfer.
Port No: 119 (TCP)

IMAP
Full Name: Internet Message Access Protocol
Use: Protocol for accessing mailboxes stored on a server.
Port No: 143 (TCP)

RMI Registry
Full Name: Remote Method Invocation Registry
Use: The registry service for Java remote objects.
Port No: 1099 (TCP)

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

java.net.InetAddress
The java.net.InetAddress class provides methods to get the IP address of any hostname. An IP
address is represented by a 32-bit or 128-bit unsigned number. InetAddress can handle both IPv4
and IPv6 addresses.

InetAddress – Factory Methods :


The InetAddress class is used to encapsulate both the numerical IP address and the domain name
for that address. The InetAddress class has no visible constructors. The InetAddress class has the
inability to create objects directly, hence factory methods are used for the purpose. Factory
Methods are static methods in a class that return an object of that class.

public static InetAddress getLocalHost() throws UnknownHostException - This method


returns the instance of InetAddress containing the local hostname and address.
public static InetAddress getByName( String host ) throws UnknownHostException - This
method returns the instance of InetAddress containing IP and Host name of host represented by
host argument.
public static InetAddress[] getAllByName( String hostName ) throws
UnknownHostException - This method returns the array of the instance of InetAddress class
which contains IP addresses.
public static InetAddress getByAddress( byte IPAddress[] ) throws
UnknownHostException - This method returns an InetAddress object created from the raw IP
address.
public static InetAddress getByAddress( String hostName, byte IPAddress[] ) throws
UnknownHostException -This method creates and returns an InetAddress based on the
provided hostname and IP address.

Instance Methods
equals(Object other) - Returns true if this object has the same Internet address as other.
getAddress() - Returns a byte array that represents the object’s Internet address in network byte
order.
getHostAddress() - Returns a string that represents the host address associated with the
InetAddress object.
getHostName() - Returns a string that represents the host name associated with the InetAddress
object.
isMulticastAddress() - Returns true if this Internet address is a multicast address; otherwise,
returns false.
toString() - Returns a string that lists the host name and the IP address for convenience.

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

Client and Server Overview


Client
● Role: Initiates communication with the server to request resources or services.
● Listens: Clients generally do not listen for incoming connections; they initiate requests to
a specific server and port.
● Connections: Establishes a connection to the server, usually via a specific protocol (e.g.,
HTTP, FTP, SMTP).
● Requests: Sends requests to the server, which could include data, file requests, or service
queries.
● Receives: Waits for a response from the server, which typically includes the requested
data or an acknowledgment.
● Examples: Web browsers, email clients, FTP clients.

Server
● Role: Waits for incoming requests from clients and provides resources or services in
response.
● Listens: Servers actively listen on specific ports for incoming client connections.
● Connections: Accepts connections from clients, establishing a communication channel
for data exchange.
● Processes Requests: Handles client requests, performs necessary operations (like database
queries), and generates responses.
● Sends Responses: Sends data back to the client or confirms that the requested operation
was successful.
● Examples: Web servers (e.g., Apache, Nginx), database servers (e.g., MySQL), file
servers (e.g., FTP servers).

Working of Socket

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

● 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.

TCP/IP Server Socket


ServerSockets are quite different from normal Sockets. When we create a ServerSocket, it will
register itself with the system as having an interest in client connections. The constructors for
ServerSocket reflect the port number that we wish to accept connections on and, optionally, how
long we want the queue for said port to be. The queue length tells the system how many client
connections it can leave pending before it should simply refuse connections. The default is 50.

Create a ServerSocket:
A new ServerSocket is instantiated on a specified port using the ServerSocket() constructor.

Listen for Connections:


The ServerSocket listens for incoming connection attempts using its accept() method.
The accept() method blocks until a client attempts to connect.

Establish Connection:
Once a client connects, the accept() method returns a Socket object, which represents the
connection between the server and the client.

Obtain Streams for Communication:


Based on the server's needs, either the Socket's getInputStream() or getOutputStream() method
(or both) is called to retrieve input and output streams for communication with the client.

Server-Client Interaction:
The server and the client exchange data following a predefined protocol.

Close the Connection:


When the interaction is complete, the connection is closed by either the server, the client, or
both.

Wait for Next Connection:


The server returns to step 2, waiting for the next client connection.

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

ServerSocket Constructors
ServerSocket(int port)
Description: Creates a server socket bound to the specified port. The queue length defaults to 50,
meaning that up to 50 incoming connection requests can be queued while the server is busy.
Throws:
BindException if the port is already in use.
IOException for general I/O errors.

ServerSocket(int port, int maxQueue)


Description: Creates a server socket bound to the specified port with a queue length of
maxQueue. This determines how many incoming connection requests can be queued before the
server starts refusing new connections.
Throws:
BindException if the port is already in use.
IOException for other I/O errors.

ServerSocket(int port, int maxQueue, InetAddress localAddress)


Description: Creates a server socket bound to the specified port, with a queue length of
maxQueue. For multi-homed hosts (those with multiple network interfaces), the localAddress
specifies the IP address on which to bind the server socket.
Throws:
IOException for general I/O errors.

Methods
accept()
Description: Blocks and waits for a client to connect. Once a connection is made, it returns a
Socket object.
Signature: public Socket accept() throws IOException

close()
Description: Closes the ServerSocket, freeing up the port and terminating all active connections.
Signature: public void close() throws IOException

getInetAddress()
Description: Returns the local IP address to which the ServerSocket is bound. If not bound, it
returns null.
Signature: public InetAddress getInetAddress()

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

getLocalPort()
Description: Returns the port number on which the ServerSocket is listening. If it is not bound, it
returns -1.
Signature: public int getLocalPort()

URL
The URL (Uniform Resource Locator) is a standardized way to uniquely identify and locate
resources on the Internet. Tim Berners-Lee devised URLs to provide a scalable method for
naming resources, which became fundamental to the Web's functionality.

URL Components:
Protocol: The communication method, such as http, ftp, file, etc. (e.g., http://).
Host Name or IP Address: The server's address, delimited by // and / (e.g., www.rediff.com).
Port Number (optional): Specifies the communication port, delimited by a colon : (e.g., :80 for
HTTP, which is often defaulted).
File Path: The path to the specific file or resource on the server (e.g., /index.htm).
Java’s URL class provides an API for handling and accessing information via URLs. It includes
constructors for specifying URLs, and they can throw a MalformedURLException if the format
is invalid.

The URL https://darshankhapekar.web.app/ can be broken down into the following four
components:
Protocol: https
Specifies the communication protocol (HyperText Transfer Protocol Secure).
Host Name: darshankhapekar.web.app
The domain name of the host server.
Port Number: (Implicit, not shown)
The port number is not explicitly mentioned, but it defaults to port 443 for https.
File Path: /
The root directory or default resource (this could load an index.html file on the server).

Constructor
URL(String urlSpecifier)
This constructor creates a URL from a single string, where the string contains the full URL
(protocol, host, optional port, and path).

URL(String protName, String hostName, int port, String path)


This constructor allows you to specify the protocol, host name, port number, and file path as
separate components.

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

URL(String protName, String hostName, String path)


Similar to the above, but without the port number. It assumes the default port for the specified
protocol (e.g., port 80 for HTTP, 443 for HTTPS).

URL(URL urlObj, String urlSpecifier)


This constructor allows you to create a new URL using an existing URL object as a reference or
base context. The new URL is formed by combining the existing URL with a relative or absolute
path provided in the urlSpecifier.

URLConnection Class
URLConnection is an abstract class that represents an active connection to a resource specified
by a URL.
It provides more control over server interactions compared to the URL class, especially with
HTTP servers.

Key Features:
Header Management: Inspect and modify headers sent to and received from the server.
Binary Data Transfer: Supports downloading binary files.
HTTP Methods: Allows sending data to servers using methods like POST or PUT.
Custom Configuration: The URLConnection object can be configured before interacting with the
server.

Basic Steps to Use URLConnection:


● Construct a URL object.
● Open Connection: Use the openConnection() method on the URL object to get a
URLConnection.
● Configure the Connection (Optional).
● Read Header Fields (Optional).
● Get Input Stream: Read data from the server.
● Get Output Stream: Send data to the server (if needed).
● Close the Connection.
● Not all steps are necessary depending on the task:

Step 3 (configuration) is optional if defaults suffice.


Step 4 (header inspection) is optional if headers are not important.
Step 6 (output stream) is skipped if only reading data.

The class constructor is protected, meaning it is designed to be subclassed and is not instantiated
directly. Instead, use the openConnection() method from a URL object to retrieve a
URLConnection instance.

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

Steps to Retrieve Data from a Server using URLConnection:


● Construct a URL object.
● Open Connection: Call openConnection() on the URL object to get a URLConnection
object.
● Get Input Stream: Use getInputStream() to get data from the server.
● Read Data: Read data using standard input stream methods.

Differences Between URL and URLConnection:


URLConnection gives access to HTTP headers.
URLConnection can configure request parameters (e.g., HTTP headers).
URLConnection can write data to the server (POST, PUT) in addition to reading data.

Reading HTTP Headers with URLConnection:


HTTP servers provide details like content type, length, and modification dates in headers.
These headers can be read using methods in URLConnection.

Key Methods of URLConnection:


getContentType(): Returns the MIME content type (e.g., text/html, image/gif).
getContentLength(): Returns the content length in bytes (or -1 if not available).
getDate(): Returns the document's send date (milliseconds since Jan 1, 1970, GMT).
getExpiration(): Returns the expiration date of the document (useful for caching).
getLastModified(): Returns the last modification date of the document.

Important Methods of URLConnection:


Data Retrieval:
getInputStream(): Returns an InputStream to read data from the URL

Retrieving Arbitrary Header Fields:

getHeaderField(String name): Returns the value of a named header field.


Example: String contentType = uc.getHeaderField("Content-Type");
getHeaderFieldKey(int n): Returns the name of the nth header field.
getHeaderField(int n): Returns the value of the nth header field.

Overview of Datagrams
Definition: Datagrams are packets of information sent over a network without guarantees of
delivery or order, contrasting with TCP's reliable stream.

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

Usage: Useful in scenarios where speed is critical and occasional packet loss is acceptable.
Key Classes
DatagramPacket: Represents a packet of data to be sent or received.

Constructors for Receiving:


DatagramPacket(byte[] buffer, int length)
DatagramPacket(byte[] buffer, int offset, int length)

Constructors for Sending:


DatagramPacket(byte[] data, int length, InetAddress destination, int port)
DatagramPacket(byte[] data, int offset, int length, InetAddress destination, int port)

DatagramSocket: Handles sending and receiving of DatagramPacket objects.

Constructors:
DatagramSocket()
DatagramSocket(int port)
DatagramSocket(int port, InetAddress interface)

DatagramPacket Methods
Get Methods:
getAddress(): Returns the remote host's address.
getPort(): Returns the remote port.
getSocketAddress(): Returns the complete socket address (IP and port).
getData(): Returns the data array.
getLength(): Returns the number of bytes of data in the packet.
getOffset(): Returns where the data starts in the array.

Set Methods:
setData(byte[] data): Changes the packet's data.
setAddress(InetAddress remote): Changes the destination address.
setPort(int port): Changes the destination port.
setLength(int length): Changes the number of bytes considered as data.

DatagramSocket Methods
Sending and Receiving:

send(DatagramPacket dp): Sends a datagram packet.


receive(DatagramPacket dp): Receives a datagram packet, blocking until one arrives.
Closing and Connection:

Prepared by Darshan Sir


V2V Classes Advanced Java Programming

close(): Frees the port used by the socket.


connect(InetAddress host, int port): Restricts communication to a specific host and port.
disconnect(): Breaks the connection to allow communication with any host/port.

Prepared by Darshan Sir

You might also like