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

Chap 04 Networking Basics

Uploaded by

priyabhat530
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)
24 views38 pages

Chap 04 Networking Basics

Uploaded by

priyabhat530
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

ADVANCE JAVA PROGRAMMING

CHAPTER 04

NETWORKING BASICS
BY
MR.RUPNAR PRAVIN MARUTI
M.TECH CST
The Objectives Of This Chapter Are:

To discuss the Sockets.


To understand the hierarchy of Java and the Net.
To understand the InetAddress Class.
To understand URL and URL Connection Class.
To understand Datagram Class.
What Is a Socket?
Normally, a server runs on a specific computer and has a socket that is bound to a specific
port number. The server just waits, listening to the socket for a client to make a connection
request.
On the client-side: The client knows the hostname of the machine on which the server is running
and the port number on which the server is listening. To make a connection request, the client
tries to rendezvous with the server on the server's machine and port. The client also needs to
identify itself to the server so it binds to a local port number that it will use during this
connection. This is usually assigned by the system
if everything goes well, the server accepts the connection. Upon acceptance, the server
gets a new socket bound to the same local port and also has its remote endpoint set to the
address and port of the client. It needs a new socket so that it can continue to listen to the
original socket for connection requests while tending to the needs of the connected client..
The port numbers are divided into three categories:

•Well-known ports
•Registered ports
•Dynamic ports
Well-known ports

The range of well-known port is 0 to 1023. The well-known ports are used with
those protocols that serve common applications and services such as
HTTP (hypertext transfer protocol), IMAP (Internet Message Access Protocol),
SMTP (Simple Mail Transfer Protocol), etc. For example, we want to visit some
websites on an internet; then, we use http protocol; the http is available with a port
number 80, which means that when we use http protocol with an application then it
gets port number 80. It is defined that whenever http protocol is used, then port
number 80 will be used. Similarly, with other protocols such as SMTP, IMAP; well-
known ports are defined. The remaining port numbers are used for random
applications.
Registered ports
The range of registered port is 1024 to 49151. The registered ports are used for the user
processes. These processes are individual applications rather than the common
applications that have a well-known port.
Dynamic ports
The range of dynamic port is 49152 to 65535. Another name of the dynamic port is
ephemeral ports. These port numbers are assigned to the client application dynamically
when a client creates a connection. The dynamic port is identified when the client
initiates the connection, whereas the client knows the well-known port prior to the
connection. This port is not known to the client when the client connects to the service.
Proxy Server
The proxy server is like an intermediate system between the client-side application and
other servers. In an enterprise application, which is used to provide control over the
user's content across network boundaries. The below image demonstrates the behavior
of the proxy server:
Advantages of Using Proxy Servers

• The proxy servers are useful in the following cases:


• To capture the traffic between a client and server.
• To control and limit the uploading/downloading the bandwidth to discover the
loading of the website with slow connections.
• To analyze the system reaction when there is trouble in your network.
• To update the content of a client/server.
• To create statistics about traffic.
INTERNET ADDRESSING

Devices connected to the Internet are called nodes. Nodes that are computers are
called hosts. Each node or host is identified by at least one unique number called an
Internet address or an IP address. Most current IP addresses are 4-byte-long IPv4
addresses. However, a small but growing number of IP addresses are 16-byte-long IPv6
addresses. (4 and 6 refer to the version of the Internet Protocol, not the number of the
bytes in the address.) Both IPv4 and IPv6 addresses are ordered sequences of bytes, like
an array. They aren’t numbers, and they aren’t ordered in any predictable or useful
sense.
TRADITIONAL COMMUNICATION

Protocol

communication
TRADITIONAL COMMUNICATION

Translator Presentation Layer Translator

Vajir Session Layer Vajir

Communication Transport Layer Communication


Team Head Team Head

Message Network Layer Message


Transporter Transporter

Horse Man Data Link Layer Horse Man

Horse Physical Layer Horse


4.2 JAVA AND THE NET

Class Use

CookieManager provides a concrete implementation of


CookieManager CookieHandler, which separates the storage of cookies from the
policy surrounding accepting and rejecting cookies.

DatagramPacket This class represents a datagram packet.


This class represents a socket for sending and receiving datagram
DatagramSocket
packets.
Inet4Address This class represents an Internet Protocol version 4 (IPv4) address.
Inet6Address This class represents an Internet Protocol version 6 (IPv6) address.
InetAddress This class represents an Internet Protocol (IP) address.
JAVA.NET PACKAGE CLASSES

NetPermission This class is for various network permissions.


ServerSocket This class implements server sockets.
Socket This class implements client sockets (also called just "sockets").
URI Represents a Uniform Resource Identifier(URI) reference.
Class URL represents a Uniform Resource Locator, a pointer to a
URL
"resource" on the World Wide Web.
The abstract class URLConnection is the superclass of all classes
URLConnection that represent a communications link between the application and
a URL.
Interfaces of java.net package
4.2 JAVA AND THE NET

Interface Use
CookiePolicy implementations decide which
CookiePolicy cookies should be accepted and which should be
rejected.
A CookieStore object represents storage for
CookieStore
cookie.
DatagramSocketImplFact This interface defines a factory for datagram
ory socket implementations.
A simple interface which provides a mechanism to
FileNameMap map between a file name and a MIME(Multipurpose
Internet Mail Extensions) type string.
This interface defines a factory for socket
SocketImplFactory
implementations.
SocketOptions Interface of methods to get/set socket options.
URLStreamHandlerFactor This interface defines a factory for URL stream
y protocol handlers.
4.3 INETADDRESS CLASS

Java InetAddress class

Java InetAddress class represents an IP address. The java.net.InetAddress


class provides methods to get the IP of any host name for
example www.javatpoint.com, www.google.com, www.facebook.com, etc.

An IP address is represented by 32-bit or 128-bit unsigned number. An


instance of InetAddress represents the IP address with its corresponding
host name. There are two types of addresses: Unicast and Multicast. The
Unicast is an identifier for a single interface whereas Multicast is an
identifier for a set of interfaces.
FACTORY METHODS OF INETADDRESS CLASS

Method Description
public static InetAddress It returns the instance of InetAddress
getByName(String host) throws containing LocalHost IP and name.
UnknownHostException
public static InetAddress It returns the instance of InetAdddress
getLocalHost() throws containing local host name and address.
UnknownHostException
public String getHostName() It returns the host name of the IP
address.
public String getHostAddress() It returns the IP address in string format.
INSTANCE METHODS
Method
Description

This function compares this object against the


equals(Object obj)
specified object.
This method returns the raw IP address of this
getAddress()
InetAddress object, in bytes.
getHostAddress() This method gets the IP address in string form.

getHostName() This method returns the host name for this IP address.
This method used to check if the InetAddress
isLoopbackAddress()
represents a loopback address.
This method checks whether the site has multiple
isMulticastAddress()
servers.
isReachable(int
This method tests whether that address is reachable.
timeout)
TCP/IP CLIENT SOCKET

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.
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
Method Description
1) public Socket accept() returns the socket and establish a
connection between server and
client.
2) public 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=ss.accept();//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);


Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource
Locator. It points to a resource on the World Wide Web. For example:
1.https://www.javatpoint.com/java-tutorial

A URL contains many information:


2.Protocol: In this case, http is the protocol.
2.Server name or IP Address: In this case, www.javatpoint.com is the server name.
3.Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is
not mentioned in the URL, it returns -1.
4.File Name or directory name: In this case, index.jsp is the file name.
Constructors of Java URL class
URL(String spec)
Creates an instance of a URL from the String representation.

URL(String protocol, String host, String file)


Creates an instance of a URL from the given protocol name, host name, and file name.

URL(String protocol, String host, int port, String file)


Creates an instance of a URL from the given protocol, host, port number, and file.
Commonly used methods of Java URL class
The java.net.URL class provides many methods. The important methods of 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 toString() it returns the string representation of the URL.
public URLConnection it returns the instance of URLConnection i.e.
openConnection() associated with this URL.
public boolean equals(Object it compares the URL with the given object.
obj)
What is URI?

URI stands for Uniform Resource Identifier. A Uniform Resource Identifier is a


sequence of characters used for identification of a particular resource. It enables for the
interaction of the representation of the resource over the network using specific
protocols.
URI Syntax :

scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]

1.scheme : The scheme component lays out the protocols to be associated with the URI.

2.authority : Authority component is made of several components- authentication section, a


host and optional port number preceded by a ‘:’. Authentication section includes username
and password.

3.path : The path represents a string containing the address within the server to the resource.

4.query : Query represent a nonhierarchical data usually the query used for searching of a
particular resource. They are separated by a ‘?’ from the preceding part.

5.fragment : Fragments are used to identify secondary resources as headings or subheadings


within a page etc
Constructors :
1.URI(String str) : Constructs a URI object by parsing the specified string.

Syntax :
public URI(String str) throws URISyntaxException

Parameters : str : String to be parsed into URI


Throws : URISyntaxException
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.
Features of URLConnection class
1. URLConnection is an abstract class and makes the connection between the client Java program and
URL resource on the internet.
2. With the help of URLConnection class, a user can read and write to and from any resource
referenced by an URL object.
3. Once a connection is established and the Java program has an URLConnection object, we can use it
to read or write or get further information like content length, etc.

Constructors

Constructor Description

1) protected URLConnection(URL url) It constructs a URL connection to the


specified URL.
URLCONNECTION CLASS METHODS
Method Description
void connect() It opens a communications link to the resource referenced
by this URL, if such a connection has not already been
established.
int getConnectionTimeout() It returns setting for connect timeout.
Object getContent() It retrieves the contents of the URL connection.
String getContentEncoding() It returns the value of the content-encoding header field.
int getContentLength() It returns the value of the content-length header field.
String getContentType() It returns the value of the date header field.
long getExpiration() It returns the value of the expires header files.
InputStream getInputStream() It returns an input stream that reads from the open condition.
long getLastModified() It returns the value of the last-modified header field.
DATAGRAMS IN JAVA

Clients and servers that communicate via a reliable channel, such as a


TCP socket, have a dedicated point-to-point channel between themselves. To
communicate, they establish a connection, transmit the data, and then close the
connection. All data sent over the channel is received in the same order in which it was
sent. This is guaranteed by the channel.
In contrast, applications that communicate via datagrams send and
receive completely independent packets of information. These clients and servers do not
have and do not need a dedicated point-to-point channel. The delivery of datagrams to
their destinations is not guaranteed. Nor is the order of their arrival.
DatagramSocket defines four public constructors. They are shown here:

DatagramSocket( ) throws SocketException : It creates a DatagramSocket bound to any


unused port on the local computer.

DatagramSocket(int port) throws SocketException : It creates a DatagramSocket bound


to the port specified by port.

DatagramSocket(int port, InetAddress ipAddress) throws SocketException : It


constructs a DatagramSocket bound to the specified port and InetAddress.

DatagramSocket(SocketAddress address) throws SocketException : It constructs a


DatagramSocket bound to the specified SocketAddress.
Methods Usage
If the socket is connected, then the address is returned.
InetAddress getInetAddress( )
Otherwise, null is returned.
int getLocalPort( ) Returns the number of the local port.
Returns the number of the port to which the socket is
int getPort( ) connected. It returns –1 if the socket is not connected to a
port.
Returns true if the socket is connected to a server. Returns
boolean isConnected( )
false otherwise.
void setSoTimeout(int millis) Sets the time-out period to the number of milliseconds
throws SocketException passed in millis.
DatagramSocket defines many methods. Two of the most important are send( ) and
receive( ), which are shown here:

void send(DatagramPacket packet) throws IOException


void receive(DatagramPacket packet) throws IOException

The send( ) method sends packet to the port specified by packet. The receive method
waits for a packet to be received from the port specified by packet and returns the result.
DatagramPacket defines several constructors. Four are shown here:

DatagramPacket(byte data[ ], int size) : It specifies a buffer that will receive data and the
size of a packet. It is used for receiving data over a DatagramSocket

DatagramPacket(byte data[ ], int offset, int size) : It allows you to specify an offset into
the buffer at which data will be stored.

DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port) : It specifies a


target address and port, which are used by a DatagramSocket to determine where the data in
the packet will be sent.

DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port) : It
transmits packets beginning at the specified offset into the data.
Function Usage
Returns the address of the source (for datagrams being
InetAddress getAddress( )
received) or destination (for datagrams being sent).
Returns the byte array of data contained in the datagram.
byte[ ] getData( ) Mostly used to retrieve data from the datagram after it has
been received.
Returns the length of the valid data contained in the byte
int getLength( ) array that would be returned from the getData( ) method.
This may not equal the length of the whole byte array.

int getOffset( ) Returns the starting index of the data.

void setPort(int port) Sets the port to port.


Function Usage
int getPort( ) Returns the port number.

void setAddress(InetAddress Sets the address to which a packet will be sent. The
ipAddress) address is specified by ipAddress.

Sets the data to data, the offset to zero, and the length to
void setData(byte[ ] data)
number of bytes in data

void setData(byte[ ] data, int Sets the data to data, the offset to idx, and the length to
idx, int size) size.

void setLength(int size) Sets the length of the packet to size.

You might also like