0% found this document useful (0 votes)
2 views

unit 3 part 2 networking

Uploaded by

khushisingh7628
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

unit 3 part 2 networking

Uploaded by

khushisingh7628
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

Java Networking Terminology:

1) 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.
What is Port?
A port is an access point where protocols are used in a network to locate
the particular processes or services within a device. It is several 16 bits
that can have a value between 0 and 65535 and can be used for
discriminating one application or service from others running on the same
host. Ports enable the right forwarding of the network connections where
the data packets are directed to the right location of the application.

Socket:
A socket can be regarded as a basic network entity that allows devices to
communicate over a network with the use of data. It is used in a
communication chain and acts as an accepting and transmitting centre for
data from the applications. Sockets are a way to enable programs to
communicate with others using certain protocols like TCP or UDP. Socket
Socket vs port difference
Parameters Socket Port

An endpoint for sending or A numerical identifier for specific


receiving data across a services or processes on a
Definition network. device.

Identifies different
Facilitates communication
applications/services on a
between two devices.
Function device.

Consists of an IP address Consists solely of a number (0-


Components and a port number. 65535).

Exists in pairs (one on the


Single numeric value.
Type client, one on the server).
Java.net-
Package that Provides the classes for implementing networking applications.

The java.net package can be roughly divided in two sections:

 A Low Level API, which deals with the following abstractions:


 Addresses, which are networking identifiers, like IP addresses.
 Sockets, which are basic bidirectional data communication
mechanisms.
 Interfaces, which describe network interfaces.
 A High Level API, which deals with the following abstractions:
 URIs, which represent Universal Resource Identifiers.
 URLs, which represent Universal Resource Locators.
 Connections, which represents connections to the resource
pointed to by URLs.

Ipaddress: An IP address is a string of numbers separated by periods. IP


addresses are expressed as a set of four numbers — an example address might be
192.158.1.38. Each number in the set can range from 0 to 255. So, the full IP
addressing range goes from 0.0.0.0 to 255.255.255.255.

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.

Program to find ip address:

import java.net.*;

class JavaApplication2 {
public static void main(String args[])
throws UnknownHostException
{
// The URL for which IP address needs to be fetched
String s = "https://www.google.com/";

try {
// Fetch IP address by getByName()
InetAddress ip = InetAddress.getByName(new URL(s)
.getHost());

// Print the IP address


System.out.println("Public IP Address of: " + ip);
}
catch (MalformedURLException e) {
// It means the URL is invalid
System.out.println("Invalid URL");
}
}
}

Output: Public IP Address of: www.google.com/142.250.70.100

Java Inet Address class methods


Method Description

public static InetAddress getByName(String It returns the instance of InetAddress


host) throws UnknownHostException containing LocalHost IP and name.

public static InetAddress getLocalHost() It returns the instance of InetAdddress


throws UnknownHostException containing local host name and address.

public String getHostName() It returns the host name of the IP address.

public String getHostAddress() It returns the IP address in string format.


Factory Methods in Java
A Factory Pattern or Factory Method Pattern says that just define an interface or
abstract class for creating an object but let the subclasses decide which class to
instantiate. In other words, subclasses are responsible to create the instance of the
class.

The Factory Method Pattern is also known as Virtual Constructor.

Advantage of Factory Design Pattern

o Factory Method Pattern allows the sub-classes to choose the type of objects to
create.
o It promotes the loose-coupling by eliminating the need to bind application-specific
classes into the code. That means the code interacts solely with the resultant
interface or abstract class, so that it will work with any classes that implement that
interface or that extends that abstract class.

Factory methods Program:


interface vehicle class vehiclefactory
{ {
public void vehicleinfo(); public vehicle getvehicleinfo(string vtype)
} {
switch(vtype)
class byke implements {
vehicle case “byke”
{ return new byke;
public void vehicleinfo() case “car”
{ return new car;
System.out.print(“it’s a bike”); case “bus”
} return new car;
} }
return null;
class car implements }
vehicle
{ class demo
public void vehicleinfo() {
{ public static void main(String a[])
System.out.print(“it’s a car”); {
} vehiclefactory factory=new vehiclefactory();
} vehicle obj=factory.getvehicleinfo(“bus”);
obj.vehicleinfo();
class bus implements
}
vehicle }
{
public void vehicleinfo() Output:
{ It’s a bus
System.out.print(“it’s a bus”);
}
}

Instance methods:
Instance Methods are the group of codes that performs a particular task.
Sometimes the program grows in size, and we want to separate the logic
of the main method from other methods. A method is a function written
inside the class. Since java is an object-oriented programming language,
we need to write a method inside some classes.

The important points regarding instance variables are:


1. Instance methods can access instance variables and instance methods
directly.
2. Instance methods can access static variables and static methods
directly.

Example:
import java.io.*;
class GFG {
// static method
public static void main (String[] args) {
// Creating object of the class
GFG obj = new GFG();
// Calling instance method
obj.disp();
System.out.println("GFG!");
}
// Instance method
void disp()
{
// Local variable
int a = 20;
System.out.println(a);
}
}

Output
20
GFG!
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.

What is the URL?

o URL is an abbreviation for Uniform Resource Locator. An URL is a form of string that
helps to find a resource on the World Wide Web (WWW).
o URL has two components:

1. The protocol required to access the resource.


2. The location of the resource.

class JavaApplication4 {
public static void main(String[] args)
{
String url
= "https://www.geeksforgeeks.org/variables-in-java/";
// Calling method to get URL info
getUrlInfo(url);
}
static void getUrlInfo(String url_string)
{
// Creating object of URL class
try {
URL url = new URL(url_string);

System.out.println("Hostname: "
+ url.getHost());
System.out.println("Port Number: "
+ url.getPort());
System.out.println("File name: "
+ url.getFile());
System.out.println("Protocol: "
+ url.getProtocol());
}
catch (Exception e) {
}
}
}
Output: Hostname: www.geeksforgeeks.org
Port Number: -1
File name: /variables-in-java/
Protocol: https
Datagram:
A datagram is an independent, self-contained message sent over the
network whose arrival, arrival time, and content are not guaranteed.
 Datagrams plays a vital role as an alternative.
 Datagrams are bundles of information passed between machines.
Once the datagram has been released to its intended target, there is
no assurance that it will arrive or even that someone will be there to
catch it.
 Likewise, when the datagram is received, there is no assurance that it
hasn’t been damaged in transit or that whoever sent it is still there to
receive a response and it is crucial point to note.
Java implements datagrams on top of the UDP (User Datagram Protocol)
protocol by using two classes:
1. DatagramPacket object is the data container.
2. DatagramSocket is the mechanism used to send or receive the
DatagramPackets.

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.
TCP/IP Server Socket:TCP is a Network Protocol that
stands for Transfer Control Protocol, which allows well-
founded communication between applications. TCP is
consistently used over the Internet Protocol, and that is
why referred to as TCP/IP. The communication mechanism
between two systems, using TCP, can be established using
Sockets and is known as Socket Programming. Hence,
socket programming is a concept of Network
Programming, that suggests writing programs that are
executed across multiple systems, which are connected to
each other using a network.

The mechanism for Socket Programming


A client creates a socket at its end of transmission and
strives to connect the socket to the server. When a
connection is established, the server creates a socket at its
end and, the client and server can now ready communicate
through writing and reading methods. Following is the
elaborated procedure of what happens when a TCP
connection is established:
An object of ServerSocket is instantiated, and desired port number is specified, on which connection
is going to take place.
The accept method of ServerSocket is invoked, in order to hold the server in listening mode. This
method won’t resume until a client is connected to the server through the given port number.
Now, on the client-side, an object of Socket is instantiated, and desired port number and IP address
is specified for the connection.
An attempt is made, for connecting the client to the server using the specified IP address and port
number. If the attempt is successful, the client is provided with a Socket that is capable of
communicating to the respective server, with write and read methods. If unsuccessful, the desired
exception is raised.
Since a client is connected to the server, accept method on the server-side resumes, providing
a Socket that is capable of communicating to the connected client.
Once the communication is completed, terminate the sockets on both, the server and the client-
side.
Now, communication is held using input/output streams of Sockets. The InputStream of the client is
coupled with the OutputStream of the server and the OutputStream of the client is coupled with
the InputStream of the server. Since TCP is a two-way network protocol, hence information can flow
through both the streams at the time.
TCP/IP server Sockets:

Java has a different socket class that must be used for creating server
applications. The ServerSocket class is used to create servers that listen for
either local or remote client programs to connect to them on published
ports. ServerSockets are quite different from normal Sockets. When you
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 you want to accept connections on and, optionally, how
long you 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. The constructors might throw
an IOException under adverse conditions. Here are three of its constructors:

ServerSocket has a method called accept( ), which is a blocking call that will
wait for a client to initiate communications and then return with a
normal Socket that is then used for communication with the client.
TCP/IP client socket:
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 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:
Program for TCP/IP server Socket:
import java.io.*;
import java.net.*;
class javaApplication4{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(3336);
Socket s=ss.accept();
BufferedReader br=new BufferedReader(new
InputStreamReader(s.getInputStream()));
BufferedWriter bw=new BufferedWriter(new
OutputStreamWriter(s.getOutputStream()));
String s1=br.readLine();
System.out.println(s1);
bw.write("Thanks for contact/n");
bw.flush();
s.close();
ss.close();
}}
Program for TCP/IP client Scocket:
import java.io.*;
import java.net.*;

class javaApplication6{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",3335);

BufferedReader br=new BufferedReader(new


InputStreamReader(s.getInputStream()));
BufferedWriter bw=new BufferedWriter(new
OutputStreamWriter(s.getOutputStream()));
bw.write("hello server/n");

bw.flush();
String s1=br.readLine();
System.out.println(s1);
s.close();
}
}

You might also like