You are on page 1of 6

Lesson 1 import java.net.UnknownHostException; System.out.

println("\tSubinterfaces: " +
1.Define client server model. Explain design considerations for the client server import java.util.Arrays; Collections.list(iface.getSubInterfaces()));
application.
->Client-server model is a distributed application structure that partitions tasks or public class inet4add
workloads between the providers of a resource or service, called servers, and service { URI URL
requesters, called clients Often clients and servers communicate over a computer public static void main(String args[]) throws UnknownHostException
network on separate hardware, but both client and server may reside in the same {
system. String url = "www.geeksforgeeks.org"; URI is an acronym for Uniform Resource URL is an acronym for Uniform Resource
Inet4Address ip1 = (Inet4Address) Inet4Address.getByName(url); Identifier. Locator.
2.Explain common Networking Programming Languages. Inet4Address ip2 = (Inet4Address)
Perl: Perl is a family of script programming languages that is similar in syntax to InetAddress.getByName("www.yahoo.com");
the C language. It is an older, open source, general use, interpreted language. Perl System.out.println("Address : " + Arrays.toString(ip1.getAddress()));
URI contains two subsets, URN, which tell URL is the subset of URI, which tells the only
was developed with usability in mind. Its efficient design lets developers do a lot System.out.println("Host Address : " + ip1.getHostAddress());
the name, and URL, which tells the location of the resource.
with a little bit of code. Its nickname is the "Swiss Army chainsaw" of the internet. System.out.println("isAnyLocalAddress : " + ip1.isAnyLocalAddress());
location.
Perl is simpler to learn and code with than more structured languages, such as C System.out.println("isLinkLocalAddress : " + ip1.isLinkLocalAddress());
and C++. System.out.println("isLoopbackAddress : " + ip1.isLoopbackAddress());
Python: Python is a high-level, interpreted, general-purpose programming System.out.println("isMCGlobal : " + ip1.isMCGlobal());
All URIs cannot be URLs, as they can tell All URLs are URIs, as every URL can only
language. Its design philosophy emphasizes code readability with the use System.out.println("isMCLinkLocal : " + ip1.isMCLinkLocal());
either name or location. contain the location.
of significant indentation. Python is dynamically-typed and garbage-collected. It System.out.println("isMCNodeLocal : " + ip1.isMCNodeLocal());
supports multiple programming paradigms, System.out.println("isMCOrgLocal : " + ip1.isMCOrgLocal());
including structured (particularly procedural), object-oriented and functional System.out.println("isMCSiteLocal : " + ip1.isMCSiteLocal());
programming. System.out.println("isMulticastAddress : " + ip1.isMulticastAddress()); An example of a URI can be ISBN 0-486- An example of an URL is
JavaScript: JavaScript is a dynamic programming language that's used for web System.out.println("isSiteLocalAddress : " + ip1.isSiteLocalAddress()); 35557-4. https://www.javatpoint.com.
development, in web applications, for game development, and lots more. It allows System.out.println("hashCode : " + ip1.hashCode());
you to implement dynamic features on web pages that cannot be done with only System.out.println("ip1==ip2 : " + ip1.equals(ip2));
HTML and CSS. }
The URI scheme can be protocol, The scheme of URL is usually a protocol such
}
designation, specification, or anything. as HTTP, HTTPS, FTP, etc.
3.What is the use of Inet6 Address class? Explain with suitable example.
3.Explain different Programming tools and Platforms available in the market. In InetAddress and Inet6Address, it is used for internal representation; it has no
Network programming refers to writing programs that execute across multiple functional role. Java will never return an IPv4-mapped address. These classes can System.out.println("\this loopback: " + iface.isLoopback());
devices (computers), in which the devices are all connected to each other using a take an IPv4-mapped address as input, both in byte array and text representation. System.out.println("\this virtual: " + iface.isVirtual());
network. However, it will be converted into an IPv4 address. System.out.println("\this point to point: " + iface.isPointToPoint());
1. Wireshark (free, open source) System.out.println("Supports Multicast: " + iface.supportsMulticast());
Wireshark enables engineers to quickly get to the packet level of a problem. This }
import java.net.Inet6Address;
allows them to quickly determine if the issue is due to the network, server, service or }
import java.net.InetAddress;
client. Rather than guess at the cause of an issue, they can utilize Wireshark to see import java.net.UnknownHostException;
the real truth. NetworkInterface nif = NetworkInterface.getByIndex(1);
import java.util.Arrays;
2.Nmap (free, open source) System.out.println("Network interface 1: " + nif.toString());
Nmap provides utilities to determine what hosts are available on the network, what NetworkInterface nif2 = NetworkInterface.getByName("eth0");
public class inet6add
ports are available on those hosts, what OS and firewalls are in use and much more. InetAddress ip = InetAddress.getByName("localhost");
{
It has the capability to scan whole subnets and TCP port ranges, allowing engineers NetworkInterface nif3 = NetworkInterface.getByInetAddress(ip);
to spot problem devices and open sockets. public static void main(String[] args) throws UnknownHostException
System.out.println("\nlocalhost associated with: " + nif3);
3. iPerf3 (free, open source) {
boolean eq = nif.equals(nif2);
IPerf3 is a tool that enables engineers to measure network throughput, packet loss String host = "localhost";
System.out.println("nif==nif2: " + eq);
and jitter. If traffic congestion or link-level errors are causing packet loss, or if byte add[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 };
System.out.println("Hashcode : " + nif.hashCode());
latency has shifted affecting throughput, iPerf3 can help in isolating and resolving Inet6Address ip1 = Inet6Address.getByAddress(host, add, 5);
}
these issues. These measurements help to pinpoint whether the network is causing Inet6Address ip2 = Inet6Address.getByAddress(null, add, 6);
}
the performance problem or not. System.out.println("Scope Id : " + ip1.getScopeId());
4. Putty (free, open-source) System.out.println("Scoped Interface : " + ip1.getScopedInterface());
Putty is everywhere, even after two full decades of use. For many engineers, Putty is System.out.println("Address : " + Arrays.toString(ip1.getAddress()));
like a right hand, enabling them to access and configure network devices. Although Lesson 3
System.out.println("Host Address : " + ip1.getHostAddress());
automation is becoming king—and fancy new automation tools are entering the 1.Difference between URL and URI classes with example.
System.out.println("isAnyLocalAddress : " + ip1.isAnyLocalAddress());
market, engineers still need direct access to the infrastructure for basic setup and System.out.println("isLinkLocalAddress : " + ip1.isLinkLocalAddress());
troubleshooting. For most people, Putty is still the go-to tool for command line 2. Explain about URL and Relative URLs.
System.out.println("isLoopbackAddress : " + ip1.isLoopbackAddress());
access. A URL (Uniform Resource Locator) is a unique identifier used to locate a resource
System.out.println("isMCGlobal : " + ip1.isMCGlobal());
5.Cisco Packet Tracer: Cisco Packet Tracer is Cisco's simulation software. It can on the Internet. It is also referred to as a web address. URLs consist of multiple
System.out.println("isMCLinkLocal : " + ip1.isMCLinkLocal());
be used to create complicated network typologies, as well as to test and simulate parts including a protocol and domain name that tell a web browser how and
System.out.println("isMCNodeLocal : " + ip1.isMCNodeLocal());
abstract networking concepts. It acts as a playground for you to explore networking where to retrieve a resource.
System.out.println("isMCOrgLocal : " + ip1.isMCOrgLocal());
and the experience is very close to what you see in computer networks. A relative URL is a URL that only includes the path. The path is everything that
System.out.println("isMCSiteLocal : " + ip1.isMCSiteLocal());
comes after the domain, including the directory and slug. Because relative URLs
4.What is client/server application? System.out.println("isMulticastAddress : " + ip1.isMulticastAddress());
don't include the entire URL structure, it is assumed that when linking a relative
A client is a computer hardware device or software that accesses a service made System.out.println("isSiteLocalAddress : " + ip1.isSiteLocalAddress());
URL, it uses the same protocol, subdomain and domain as the page it's on.
available by a server. The server is often (but not always) located on a separate System.out.println("hashCode : " + ip1.hashCode());
WAP to Demonstrate the Proxy class and the Proxy Selector class.
physical computer. System.out.println("ip1==ip2 : " + ip1.equals(ip2));
import java.io.*;
A server is a physical computer dedicated to run services to serve the needs of other }
// importing java net package to use address and url fields
computers. Depending on the service that is running, it could be a file server, }
import java.net.*;
database server, home media server, print server, or web server.
import java.net.Proxy;
4.Explain about Network Interface class with suitable Program.
public class GFG {
This class represents a Network Interface made up of a name, and a list of IP public static void main(String[] args)
addresses assigned to this interface. It is used to identify the local interface on {
which a multicast group is joined. Interfaces are normally known by names such as SocketAddress addr = new InetSocketAddress(
"le0". "webcache.example.com", 8080);
import java.net.InetAddress; Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
import java.net.InterfaceAddress; try {
import java.net.NetworkInterface; URL url = new URL("http://java.example.org/");
import java.net.SocketException; URLConnection conn = url.openConnection(proxy);
import java.net.UnknownHostException; }
import java.util.ArrayList; catch (Exception e) {
import java.util.Arrays; e.printStackTrace();
5.Explain about connection-oriented networking and connectionless networking. import java.util.Collections; System.out.println(false);
A connection-oriented service is a network service that was designed and developed import java.util.Enumeration; }
after the telephone system. A connection-oriented service is used to create an end to System.out.println("Proxy Type: " + proxy.type());
end connection between the sender and the receiver before transmitting the data over public class NetworkInterfaceEx System.out.println("Proxy Address: " + proxy.address());
the same or different networks. In connection-oriented service, packets are { System.out.println("Proxy HasHCode: " + proxy.hashCode());
transmitted to the receiver in the same order the sender has sent them. It uses a public static void main(String[] args) throws SocketException, System.out.println("Proxy String: " + proxy.toString());
UnknownHostException }
handshake method that creates a connection between the user and sender for
{ }
transmitting the data over the network. Hence it is also known as a reliable network
ArrayList<NetworkInterface> interfaces = Collections.list(
service. NetworkInterface.getNetworkInterfaces()); import java.net.InetSocketAddress;
A connection is similar to a postal system, in which each letter takes along different import java.net.Proxy;
route paths from the source to the destination address. Connectionless service is used System.out.println("Information about present Network Interfaces...\n"); import java.net.ProxySelector;
in the network system to transfer data from one end to another end without creating for (NetworkInterface iface : interfaces) import java.net.SocketAddress;
any connection. So it does not require establishing a connection before sending the { import java.net.URI;
data from the sender to the receiver. It is not a reliable network service because it if (iface.isUp()) import java.util.ArrayList;
does not guarantee the transfer of data packets to the receiver, and data packets can { import java.util.List;
be received in any order to the receiver. Therefore we can say that the data packet System.out.println("Interface Name: " + iface.getName()); public class PrivateDataProxy extends ProxySelector {
does not follow a defined path. In connectionless service, the transmitted data System.out.println("Interface display name: " + iface.getDisplayName()); private final List<Proxy> noProxy = new ArrayList<>();
packet is not received by the receiver due to network congestion, and the data may System.out.println("Hardware Address: " + private final List<Proxy> proxies = new ArrayList<>();
Arrays.toString(iface.getHardwareAddress())); public PrivateDataProxy()
be lost.
System.out.println("Parent: " + iface.getParent()); {
Lesson 2
System.out.println("Index: " + iface.getIndex()); noProxy.add(Proxy.NO_PROXY);
1.What is the use of Inet Address class? Explain the basic features of Inet Address System.out.println("\tInterface addresses: "); InetSocketAddress inetSocketAddress
class. for (InterfaceAddress addr : iface.getInterfaceAddresses()) = new InetSocketAddress("secure.connection.com",443);
InetAddress class is Java's encapsulation of an IP address. It is used by most of { Proxy proxy
the other networking classes, including Socket , ServerSocket , URL , System.out.println("\t\t" + addr.getAddress().toString()); = new Proxy(Proxy.Type.HTTP, inetSocketAddress);
DatagramSocket , DatagramPacket , and more. This class represents an Internet } proxies.add(proxy);
address as two fields: hostName (a String ) and address (an int ). System.out.println("\tInetAddresses associated with this interface: "); }
Enumeration<InetAddress> en = iface.getInetAddresses(); public List<Proxy> select(URI uri)
while (en.hasMoreElements()) {
2.What is the use of Inet4 Address class? Explain with suitable example. if (uri.getPath().startsWith("/confidential")) {
This class extends the InetAddress class and represents an IPv4 address. It provides {
return proxies;
methods to interpret and display useful information about IP addresses. System.out.println("\t\t" + en.nextElement().toString()); }
} return noProxy;
import java.net.Inet4Address;
System.out.println("\tMTU: " + iface.getMTU()); }
import java.net.InetAddress;
public void connectFailed(URI arg0, SocketAddress arg1, l1.setBounds(20,100, 80,30);
IOException arg2) S.N. Method and Description value.setBounds(100,100,100,30);
{ f.add(value); f.add(l1);
f.setSize(300,300);
} 1 GET f.setLayout(null);
} f.setVisible(true);
The GET method is used to retrieve information from the given server }
4.WAP to demonstrate authenticator class. using a given URI. Requests using GET should only retrieve data and }
import java.io.BufferedReader; should have no other effect on the data.
import java.io.IOException; Lesson 4
import java.io.InputStreamReader; 1.WAP to print the HTTP header.
import java.net.Authenticator; 2 HEAD package com.mkyong.web.utils;
import java.net.InetAddress;
import java.net.MalformedURLException; Same as GET, but transfers the status line and header section only.
import javax.servlet.http.HttpServletRequest;
import java.net.PasswordAuthentication; import java.util.Enumeration;
import java.net.URL; import java.util.HashMap;
3 POST
import java.util.Map;
public class AuthenticatorgetRequestingPortExample_1
{ A POST request is used to send data to the server, for example, customer
information, file upload, etc. using HTML forms. public class WebUtils {
public static void main(String[] args)
{ private Map<String, String> getHeadersInfo(HttpServletRequest request) {
try {
ClassAuthenticator obj1 =new ClassAuthenticator(); 4 PUT
Map<String, String> map = new HashMap<String, String>();
Authenticator.setDefault(new ClassAuthenticator());
URL url = new URL("https://www.javaTpoint.com"); Replaces all current representations of the target resource with the
uploaded content. Enumeration headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
BufferedReader in = new BufferedReader(new InputStreamReader(url.openS String key = (String) headerNames.nextElement();
tream())); String value = request.getHeader(key);
5 DELETE
String line; map.put(key, value);
System.out.println("Host using url.getHost ::"+url.getHost()); }
Removes all current representations of the target resource given by a
obj1.getPasswordAuthentication() ; URI. return map;
while ((line = in.readLine()) != null) { }
System.out.println(line); 2.List all the HTTP Methods. Explain any three with Suitable Example.
} 6 CONNECT
in.close();
} catch (MalformedURLException e) { Establishes a tunnel to the server identified by a given URI. 3.What is a cookie? Explain about cookie Handler, Cookies Manager, Cookies
System.out.println("Malformed URL: " + e.getMessage());
} catch (IOException e) { Policy, Cookies Store..
System.out.println("I/O Error: " + e.getMessage()); A cookie is a piece of data from a website that is stored within a web browser
7 OPTIONS
} that the website can retrieve at a later time. Cookies are used to tell the server that
} Describes the communication options for the target resource. users have returned to a particular website.
A CookieHandler object provides a callback mechanism to hook up a HTTP
public static class ClassAuthenticator extends Authenticator state management policy implementation into the HTTP protocol handler. The
{ 8 TRACE HTTP state management mechanism specifies a way to create a stateful session with
protected PasswordAuthentication getPasswordAuthentication() HTTP requests and responses.
{ Performs a message loop-back test along the path to the target resource. The cookie manager stores and sends cookies just like a web browser. If you have
this.show();
an HTTP Request and the response contains a cookie, the Cookie Manager
String username = "javaTpoint";
automatically stores that cookie and will use it for all future requests to that
String password = "java"; try {
particular web site.
return new PasswordAuthentication(username, password.toCharArray()); ClassAuthenticator obj1 =new ClassAuthenticator();
} A cookie policy is a list of all the cookies in use on your website with detailed
Authenticator.setDefault(new ClassAuthenticator());
void show() URL url = new URL("https://www.javaTpoint.com"); information about each tracker made available for end-users to provide them with
{ insights into how their personal data is being processed when visiting your domain.
int hostname = getRequestingPort(); BufferedReader in = new BufferedReader(new InputStreamReader(url.openS A cookie is information that a website puts on a user's computer. Cookies
System.out.println("Port Requesting :" + hostname); tream())); store limited information from a web browser session on a given website that
} String line; can then be retrieved in the future. They are also sometimes referred to as browser
} System.out.println("Host using url.getHost ::"+url.getHost()); cookies, web cookies or internet cookies.
} obj1.getPasswordAuthentication() ;
while ((line = in.readLine()) != null) { Lesson 5
6.Briefly describe about the URL class. WAP to construction an URL. System.out.println(line); 1.What is a URL? What are the components of URL?
Class URL represents a Uniform Resource Locator, a pointer to a "resource" }
URL is an abbreviation for Uniform Resource Locator. An URL is a form of string
on the World Wide Web. A resource can be something as simple as a file or a in.close();
that helps to find a resource on the World Wide Web (WWW).
directory, or it can be a reference to a more complicated object, such as a query to a } catch (MalformedURLException e) {
System.out.println("Malformed URL: " + e.getMessage()); URL has two components
database or to a search engine. a) The protocol required to access the resource.
import java.net.MalformedURLException; } catch (IOException e) {
System.out.println("I/O Error: " + e.getMessage()); b) The location of the resource.
import java.net.URL;
} The Java URLConnection class represents a communication link between the URL
public class GFG {
} and the application.
public static void main(String[] args)
It can be used to read and write data to the specified resource referred by the URL.
throws MalformedURLException
{ public static class ClassAuthenticator extends Authenticator
URL url1 = new URL( { 2.Write a program to download a page and read its properties.
"https://www.google.co.in/?gfe_rd=cr&ei=ptYq" protected PasswordAuthentication getPasswordAuthentication() import java.io.*;
{ import java.net.MalformedURLException;
+ "WK26I4fT8gfth6CACg#q=geeks+for+geeks+java");
this.show(); import java.net.URL;
URL url2 = new URL("http", "www.geeksforgeeks.org",
String username = "javaTpoint";
"/jvm-works-jvm-architecture/");
String password = "java"; public class UrlDownload {
return new PasswordAuthentication(username, password.toCharArray()); public static void main(String[] args) {
URL url3 = new URL(
} try {
"https://www.google.co.in/search?"
+ "q=gnu&rlz=1C1CHZL_enIN71" void show() URL url = new URL("http://www.hubberspot.com");
+ "4IN715&oq=gnu&aqs=chrome..69i57j6" { BufferedReader reader = new BufferedReader (new
+ "9i60l5.653j0j7&sourceid=chrome&ie=UTF" int hostname = getRequestingPort(); InputStreamReader(url.openStream()));
System.out.println("Port Requesting :" + hostname); BufferedWriter writer = new BufferedWriter
+ "-8#q=geeks+for+geeks+java");
} while ((line = reader.readLine()) != null) {
System.out.println(url1.toString());
} writer.write(line);
System.out.println(url2.toString());
System.out.println(); } writer.newLine();
System.out.println( }
"Different components of the URL3-"); import java.io.*; reader.close();
System.out.println("Protocol:- "+ url3.getProtocol()); import java.net.PasswordAuthentication writer.close();
System.out.println("Hostname:- " + url3.getHost()); class GFG { }
System.out.println("Default port:- " + url3.getDefaultPort()); public static void main(String args[]) catch (MalformedURLException e) { e.printStackTrace();
System.out.println("Query:- " + url3.getQuery()); { } catch (IOException e) {e.printStackTrace();
System.out.println("Path:- " + url3.getPath()); GFG acc = new GFG(); }
System.out.println("File:- " + url3.getFile()); acc.proceed(); }
System.out.println("Reference:- " + url3.getRef()); }
} private void proceed() }
} { 3.What is URL Connection? Explain the basis steps to use the URL Connection
String userName = "Geek"; Class and write a suitable program sample.
7.WAP to demonstrate the AUTHENTICATOR CLASS, PASSWORD char[] password = { 'g', 'e', 'e', 'k', 'g', 'o', URLConnection is an abstract class whose subclasses form the link between the
'r', 'g', 'e', 'e', 'k', 's' };
AUTHENTICATION CLASS, THE JPASSWORDFIELD CLASS. user application and any resource on the web. We can use it to read/write from/to
PasswordAuthentication passwordAuthentication = new
import java.io.BufferedReader; any resource referenced by a URL object. There are mainly two subclasses that
PasswordAuthentication(userName, password);
import java.io.IOException; extend the URLConnection class.
System.out.println("UserName: + passwordAuthentication.getUserName());
import java.io.InputStreamReader; System.out.println("Password: "+ passwordAuthentication.getPassword()); ->Create a URL .
import java.net.Authenticator; System.out.println("Password: " + String.copyValueOf( ->Retrieve the URLConnection object.
import java.net.InetAddress; passwordAuthentication.getPassword())); ->Set output capability on the URLConnection .
import java.net.MalformedURLException; } ->Open a connection to the resource.
import java.net.PasswordAuthentication; } ->Get an output stream from the connection.
import java.net.URL; import javax.swing.*; ->Write to the output stream.
public class PasswordFieldExample { ->Close the output stream.
public class AuthenticatorgetRequestingPortExample_1 public static void main(String[] args) { import java.io.*;
{ JFrame f=new JFrame("Password Field Example"); import java.net.*;
public static void main(String[] args) JPasswordField value = new JPasswordField(); public class URLConnectionExample {
{ JLabel l1=new JLabel("Password:"); public static void main(String[] args){
try{ }
URL url=new URL("http://www.javatpoint.com/java-tutorial"); }
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream(); 4. what should we consider for configuring ssl server socket?
int i; Secure Sockets Layer (SSL) configurations contain the attributes that you need to
while((i=stream.read())!=-1){ control the behavior of client and server SSL endpoints.
System.out.print((char)i);
You create SSL configurations with unique names within specific management
}
Lesson 7 scopes on the inbound and outbound tree in the configuration topology.
}catch(Exception e){System.out.println(e);}
} Yo chapter ko files laptop ma kaa save gareko betirako xaina This task shows you how to define SSL configurations, including quality of
} Bhare tra khojxu ani feri pathauxu hai ta protection and trust and key manager settings.
You must decide at which scope you need to define an SSL configuration, for
3.How do you read data from server? Explain with an example. instance, the cell, node group, node, server, cluster, or endpoint scope,
1.Construct a URL object. from the least specific to the most specific scope. When you define an SSL
2.Invoke the URL object's openConnection( ) method to retrieve a URLConnection Lesson 8 configuration at the node scope, for example, only those processes within that
object for that URL. 1. what is JSSE? explain in context to secure communication. node can load the SSL configuration; however, any processes at the endpoint in the
3.Invoke the URLConnection 's getInputStream( ) method. The Java Secure Socket Extension (JSSE) enables secure Internet communications. cell can use an SSL configuration at the cell scope, which is higher in
4.Read from the input stream using the usual stream API. It provides a framework and an implementation for a Java version of the SSL the topology.
and TLS protocols and includes functionality for data encryption, server
import java.io.*; authentication, message integrity, and optional client authentication. Lesson 9
import java.net. ; The Java Secure Socket Extension (JSSE) enables secure Internet communications. 1. Write the difference between Blocking and Non-Blocking I/O.
public class URLConnectionExample{
It provides a framework and an implementation for a Java version of the SSL
public static void main(String[] args){
and TLS protocols and includes functionality for data encryption, server ANS:
try{
URC new URL("http://www.tufohss.edu.np/index.php/notices/"); authentication, message integrity, and optional client authentication. Using JSSE, Blocking I/O
URLConnectior(rIco) openConnection(); developers can provide for the secure passage of data between a client and a server (1)It is based on the Blocking I/O operation
InputStream stream rurcgetInputStream(); running any application protocol (such as HTTP, Telnet, or FTP) over TCP/IP. (2)It is Stream-oriented
int i; For an introduction to SSL, see Secure Sockets Layer (SSL) Protocol Overview. (3)Channels are not available
while((i = stream.read()) != -1){ By abstracting the complex underlying security algorithms and handshaking (4)Selectors are not available
System.out.print((char)i); mechanisms, JSSE minimizes the risk of creating subtle but dangerous security (5)Blocking IO wait for the data to be write or read before returning.
}} vulnerabilities. Furthermore, it simplifies application development by serving as a
catch(Exception e){System.out.println(e);} building block that developers can integrate directly into their applications. Non-Blocking I/O.
}} 1. It is based on the Non-blocking I/O operation
2. write short note on 2. It is Buffer-oriented
6.Write about the Web Cache for Java. event handler 3. Channels are available for Non-blocking I/O operation
Oracle Web Cache is a content acceleration and assembly solution designed to In programming, an event handler is a callback routine that operates asynchronously 4. Selectors are available for Non-blocking I/O operation
scale the middle-tier infrastructure and improve end-user experience. By once an event takes place. It dictates the action that follows the event. The 5. Non blocking IO does not wait for the data to be read or write before returning.
caching the frequently requested Web content in memory, Oracle Web Cache programmer writes a code for this action to take place. An event is an action that
effectively offloads application servers and database from repeatedly processing
takes place when a user interacts with a program. An event is an action that takes
those requests.
place when a user interacts with a program. For example, an event can be a mouse 2. What are the fundamental components of Java NIO?
Web caching is the activity of storing data for reuse, such as a copy of a web page
click or pressing a key on the keyboard. An event can be a single element or even an ANS: Java has provided a second I/O system called NIO (New I/O). Java NIO
served by a web server. It is cached or stored the first time a user visits the page
and the next time a user requests the same page, a cache will serve the copy, which HTML document. Let's say a mouse click on a button displays the message "DOM provides the different way of working with I/O than the standard I/O API's.
helps keep the origin server from getting overloaded. Event." The event handler will be the programmed routine whereby each time a user It supports a buffer-oriented, channel based approach for I/O operations. With the
clicks on the button, the message "DOM Event" is displayed. introduction of JDK 7, the NIO system is expanded, providing the enhanced support
7.What are proxy and Streaming Mode? for file system features and file-handling. Due to the capabilities supported by the
A proxy server is a system or router that provides a gateway between users and the client mode NIO file classes, NIO is widely used in file handling.
internet. Therefore, it helps prevent cyber attackers from entering a private network. the ssl serversocket has two methods for determining and specifying whether client NIO was developed to allow Java programmers to implement high-speed I/O
It is a server, referred to as an “intermediary” because it goes between end-users and sockets are required to authenticate themselves to the server. by passing true to the without using the custom native code. NIO moves the time-taking I/O activities like
the web pages they visit online. setNeedClientAuth()method you specify that only connections where the client is filling, namely and draining buffers, etc back into the operating system, thus allows
Streaming Mode automatically identifies audio and video streams, and then able to authenticate itself will be accepted. By passing false you specify that for great increase in operational speed.
Provides Quality of Service (QoS) by prioritizing streaming traffic over other types authentiation is not required of clients the default is false.
of web traffic, so that web browsing and software updates won't mess up your calls Java NIO fundamental components are given below:
and live streams. Monitors how much bandwidth your stream requires and session management
watches the statistics on how each of your Internet connections is behaving. Session management refers to the process of securely handling multiple requests to a (a) Channels and Buffers: In standard I/O API the character streams and byte
Automatically switch the streams between bonding and redundancy based on
web-based application or service from a single user or entity. Websites and browsers streams are used. In NIO we work with channels and buffers. Data is always written
which will work better. It's dynamic, so you get exceptional performance, even if
use HTTP to communicate, and a session is a series of HTTP requests and from a buffer to a channel and read from a channel to a buffer.
you're on a moving train where the best settings may change minute by minute.
transactions initiated by the same user.
(b) Selectors: Java NIO provides the concept of "selectors". It is an object that can
be used for monitoring the multiple channels for events like data arrived, connection
opened etc. Therefore single thread can monitor the multiple channels for data.
3. Mentoin the general steps for creating secure server socket.
steps: (c) Non-blocking I/O: Java NIO provides the feature of Non-blocking I/O. Here the
1 genetate public keys and certificates using keytool. application returns immediately whatever the data available and application should
2 pay money to get the certificate authenticated for trusted third party. have pooling mechanism to find out when more data is ready.
3 create an ssl context for algorithm you use.
4 create TrustManager factory 3. Describe the following:
Lesson 6 5 create keymanager factory. a. Draining Buffer
1.What is socket? How do you read from Server with Sockets? 6 create keystore object
A socket is one endpoint of a two-way communication link between two 7 fill keystore object with your key and certificate.
programs running on the network. A socket is bound to a port number so that the 8 iniatialize keymanager factory b. Flipping Buffer
TCP layer can identify the application that data is destined to be sent to. 9 iniatialize the context with necessary keymanager trustmanager. The flip() method of java.nio.ByteBuffer Class is used to flip this buffer. The limit is
Socket socket = new Socket("time.nist.gov", 13); example: set to the current position and then the position is set to zero. If the mark is defined
socket.setSoTimeout (15000); import java.net.*; then it is discarded. After a sequence of channel-read or put operations, invoke this
InputStream in = socket.getInputStream(); import java.io.*; method to prepare for a sequence of channel-write or relative get operations.
StringBuilder time = new StringBuilder();
import javax.net.ssl.*;
InputStreamReader reader = new InputStreamReader(in, "ASCII");
for (int c = reader.read(); c != -1; c = reader.read()) { For example:
time.append((char) c); public class SSLSocketClient { buf.put(magic); // Prepend header
} in.read(buf); // Read data into rest of buffer
System.out.println(time); public static void main(String[] args) throws Exception { buf.flip(); // Flip buffer
socket.close (); try { out.write(buf); // Write header + data to channel
2.Explain with appropriate example for writing to Server with Sockets. SSLSocketFactory factory =(SSLSocketFactory)SSLSocketFactory.getDefault();
Open a socket to a server SSLSocket socket =(SSLSocket)factory.createSocket("www.verisign.com",443); This method is often used in conjunction with the compact() method when
Socket socket = new Socket ("dict.org", 2628); socket.startHandshake(); transferring data from one place to another.
socket.setSoTimeout(15000); Syntax:
OutputStream out = socket.getOutputStream(); Writer writer = new PrintWriter out = new PrintWriter( new BufferedWriter( public Buffer flip()
OutputStreamWriter(out, "UTF-8"); new OutputStreamWriter(socket.getOutputStream())));
writer.write("Close\r\n"); out.println("GET / HTTP/1.0");
writer. flush(); out.println(); example:
Socket.close(); out.flush(); import java.nio.*;
3.List and explain the basic constructors of Socket Class. import java.util.*;
Each Socket constructor specifies the host and the port to connect to. if (out.checkError())
Hosts may be specified as an InetAddress or a String. System.out.println( "SSLSocketClient: java.io.PrintWriter error"); public class GFG {
Remote ports are specified as int values from 1 to 65535: public static void main(String[] args)
public Socket(String host, int port) throws Unknown HostException, BufferedReader in = new BufferedReader( new InputStreamReader( {
IOException socket.getInputStream()));
public Socket(InetAddress host, int port) throws IOException byte[] bb = { 10, 20, 30 };
String inputLine;
while ((inputLine = in.readLine()) != null) ByteBuffer byteBuffer = ByteBuffer.wrap(bb);
System.out.println(inputLine);
Buffer buffer = (Buffer)byteBuffer;
in.close(); buffer.position(1);
out.close(); System.out.println("Buffer before flip: "
socket.close(); + Arrays.toString((byte[])buffer.array())
+ "\nPosition: " + buffer.position()
} catch (Exception e) { e.printStackTrace(); + "\nLimit: " + buffer.limit());
}
buffer.flip(); 3.Adds only checksum and process-to-process addressing to IP. are used to find the multicast groups and build routes for them. Distance Vector
System.out.println("\nBuffer after flip: " 4.Used for DNS and NFS. Multicast protocol is one of them. The receiver, to whom the multicast packet is
+ Arrays.toString((byte[])buffer.array()) 5.Used when socket is opened in datagram mode. sent to, needs to ‘join’ the group. Joining the group is enabled and managed by
+ "\nPosition: " + buffer.position() 6.It sends bulk quantity of packets. IGMP. Multicast routers are used to transmit the messages from one network to
+ "\nLimit: " + buffer.limit()); 7.No acknowledgment. another.
} 8.Good for video streaming it is an unreliable protocol. Multicasting works in similar to Broadcasting, but in Multicasting, the information is
9.It does not care about the delivery of the packets or the sequence of delivery. sent to the targeted or specific members of the network. This task can be
}
10No flow control /congestion control, sender can overrun receiver's buffer. accomplished by transmitting individual copies to each user or node present in the
11.Real time application like video conferencing needs (Because it is faster). network but sending individual copies to each user is inefficient and might increase
4. Define Selector and its methods. 12An UDP datagram is used in Network File System (NFS), DNS, SNMP, TFTP etc. the network latency. To overcome these shortcomings, multicasting allows a single
ANS: The java.nio.channels.Selector class is the crucial component of nonblocking 13.It has no handshaking or flow control. transmission that can be split up among the multiple users, consequently, this
I/O. It is the class that enables your program to determine which channels are ready 14.It not even has windowing capability. reduces the bandwidth of the signal.
to be accessed when. The only constructor is protected, and subclassing this class 15.It is a fire and forget type protocol.
yourself would be unusual. Instead, you create a Selector by opening it with the 2.Explain why use multicasting.
static Selector.open( ) method: 2.Write notes on DatagramSocket and DatagramPacket class. The multicasting technology offers great advantages to the success of some
public static Selector open( ) throws IOException advanced applications. A few of these uses and advantages are presented below.
Each Selector may be registered with several SelectableChannels.Registration is Datagram-Datagrams are collection of information sent from one device to another 1.optimized network performance:
threadsafe and ongoing. You can register the Selector with various channels at any The intelligent use of network resources avoids unnecessary flow replication. This
device via the established network. When the datagram is sent to the targeted
time. way, an economy in terms of passing band is achieved through a better
device, there is no assurance that it will reach to the target device safely and architecture to distribute the data.
When your program has a little time to do some work, you ask the Selector which of completely. It may get damaged or lost in between. Likewise, the receiving device 2.support to distributed applications:
its channels are ready, that is, which channels can be read or written without also never know if the datagram received is damaged or not. The UDP protocol is Multicast technology is directed towards distributed applications. Multimedia
blocking. You do this by invoking one of these three methods: applications such as distance learning and videoconference can be used in the
used to implement the datagrams in Java.
network in a measurable and effective way.
public abstract int selectNow( ) throws IOException 3.resource economy:
public abstract int select( ) throws IOException Java DatagramSocket class The cost of the network resources is reduced through the passing band economy in
public abstract int select(long timeout) throws IOException Java DatagramSocket class represents a connection-less socket for sending and the links and the processing economy in servers and network equipment. New
receiving datagram packets. It is a mechanism used for transmitting datagram applications and services can be implanted, without requiring the renovation of
All three methods return the number of keys whose readiness states were changed by packets over network.` network resources.
this selection.The selectNow( ) method is nonblocking, whereas the other two Commonly used Constructors of DatagramSocket class 4.scalability:
methods block. selectNow( ) returns immediately even if it can't select anything. The DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it The effective use of the network and the reduction of the load in traffic sources
with the available Port Number on the localhost machine. permit services and applications to be accessed by a great number of participants.
other two methods return only after they select some channel, the thread is
DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and Consequently, services that run on multicast can be easily dimensioned,
interrupted, or the timeout expires. Even in nonblocking I/O, you tend to use
binds it with the given Port Number. distributing packages both to few and to a lot of receivers.
blocking selects if there's nothing for the program to do except I/O. However, if your DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a 5.more network availability:
program can do something useful even when no channel is ready, you might use datagram socket and binds it with the specified port number and host address. The economy of network resources associated to the reduction of the load in the
selectNow( ) instead of select( ). applications and servers makes the network less susceptible to jams, and,
Java DatagramSocket class therefore, more available to be used.
After you've called one of these methods, the selectedKeys( ) method returns a Java DatagramSocket class represents a connection-less socket for sending and
java.util.Set containing keys for all the ready channels registered with this Selector. receiving datagram packets. It is a mechanism used for transmitting datagram
public abstract Set selectedKeys( ) packets over network.`
Lesson 12
Selectors may use native system resources. Once you're done with one, you should Commonly used Constructors of DatagramSocket class
close it by invoking its close( ) method: DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it
with the available Port Number on the localhost machine. 1.What is the method used by RMI client to connect to remote RMI servers?
DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and
public abstract void close( ) throws IOException
binds it with the given Port Number. package example. hello;
DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a import java.rmi.Remote;
Otherwise, your program may leak memory and other resources, though details vary datagram socket and binds it with the specified port number and host address. import java.rmi.RemoteException;
by platform. Closing a Selector deregisters all its associated keys and wakes up any public interface Hello extends Remote {
threads waiting on the select( ) methods. Any further attempts to use a closed String sayHello() throws RemoteException;
Selector or one of its keys throws an exception. If you don't know whether a Selector }//defining remote interface
is closed, you can check with the isOpen( ) method: Example of Sending DatagramPacket by DatagramSocket package example.hello;
public abstract boolean isOpen( ) import java.rmi.registry.Registry;
import java.rmi.registry.LocateRegistry;
//DSender.java
5. Describe the channels in Java Nonblocking I/O. import java.rmi.RemoteException;
import java.net.*;
import java.rmi.server.UnicastRemoteObject;
public class DSender{
public class Server implements Hello {
ANS: In Java NIO, the channel is a medium used to transports the data efficiently public static void main(String[] args) throws Exception {
public Server() {}
between the entity and byte buffers. It reads the data from an entity and places it DatagramSocket ds = new DatagramSocket();
public String sayHello() {
inside buffer blocks for consumption. String str = "Welcome java";
return "Hello, world!";
InetAddress ip = InetAddress.getByName("127.0.0.1");
}
Channels act as gateway provided by java NIO to access the I/O mechanism. public static void main(String args[]) {
Usually channels have one-to-one relationship with operating system file descriptor DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);
try {
for providing the platform independence operational feature. ds.send(dp);
Server obj = new Server();
ds.close();
Hello stub = (Hello) UnicastRemoteObject.exportObject(obj, 0);
}
In Java NIO, channels are used for I/O transfers. Channel is a like a tube that // Bind the remote object's stub in the registry
}
transports data between a buffer and an entity at other end. A channel reads data Registry registry = LocateRegistry.getRegistry();
from an entity and places it in buffer blocks for consumption. Similarly, we should registry.bind("Hello", stub);
write to buffer blocks and that data will be transported by the channel to the other System.err.println("Server ready");
Example of Receiving DatagramPacket by DatagramSocket } catch (Exception e) {
end.
System.err.println("Server exception: " + e.toString());
e.printStackTrace();
Channels are the gateway provided by Java NIO to access the native I/O mechanism. }
//DReceiver.java
We should use buffers to interact with the channels, so the channel is like a bridge }
import java.net.*;
between two entities to do the I/O. Buffers are the endpoints provided by channels to public class DReceiver{ }//implementing server
send and receive data. public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000); package example.hello;
Java NIO Channel Classes: byte[] buf = new byte[1024];
Following are the two major types of Channels classes provided as implementation DatagramPacket dp = new DatagramPacket(buf, 1024); import java.rmi.registry.LocateRegistry;
in Java NIO package. ds.receive(dp); import java.rmi.registry.Registry;
->FileChannel String str = new String(dp.getData(), 0, dp.getLength());
These are based File read/write channels that cannot be placed on nonblocking System.out.println(str); public class Client {
ds.close(); private Client() {}
mode.
} public static void main(String[] args) {
->SocketChannel
} String host = (args.length < 1) ? null : args[0];
There are three socket channel types namely, SocketChannel, ServerSocketChannel try {
and DatagramChannel. Registry registry = LocateRegistry.getRegistry(host);
These are selectable channels that can operate in nonblocking mode. Hello stub = (Hello) registry.lookup("Hello");
Lesson 11 – IP Multicast String response = stub.sayHello();
Lesson 10 System.out.println("response: " + response);
1.Explain UDP. Mention its features. } catch (Exception e) {
1.What is multicast. Explain with examples. Describe how the multicast protocol System.err.println("Client exception: " + e.toString());
works. e.printStackTrace();
User Datagram Protocol (UDP) is a Transport Layer protocol. UDP is a part of the
}
Internet Protocol suite, referred to as UDP/IP suite. Unlike TCP, it is an unreliable
Multicast is a communication method and data delivery scheme in which a single }
and connectionless protocol. So, there is no need to establish a connection prior to }//implementing RMI client
source sends the same data to multiple receivers simultaneously. It is similar to
data transfer. 2.What are the different types of classes that are used in RMI?
broadcasting but more secure because it has an added bonus of receiver discretion,
where the data is received by specific users or hosts. The multicast process involves RMI Classes
Though Transmission Control Protocol (TCP) is the dominant transport layer a single sender and multiple receivers. versus systems that are designed to be
protocol used with most of the Internet services; provides assured delivery, connection-dependent, like a client-server system. User datagram protocol (UDP) is i.The Remote Interface. All remote interfaces extend, either directly or indirectly,
reliability, and much more but all these services cost us additional overhead and the most common protocol used with multicasting. the interface java.rmi.remote .
latency. Here, UDP comes into the picture. For real-time services like computer Email is the best example of multicast, where a user can choose to send mail to ii.The RemoteException Class. The java.
gaming, voice or video communication, live conferences; we need UDP. Since high many different addresses, rather than a complete contact list. Another example is iii.The RemoteObject Class and its Subclasses.
the one-to-many multicasting of a streaming video toward many users from a iv.Passing Nonremote Objects.
performance is needed, UDP permits packets to be dropped instead of processing
single server. Another good example is Internet protocol (IP) multicasting, where v.Passing Remote Objects.
delayed packets. There is no error checking in UDP, so it also saves bandwidth.
network nodes, like switches and routers, handle data packet replication through vi.equals and hashCode.
multicast groups. viii.toString.
User Datagram Protocol (UDP) is more efficient in terms of both latency and ix.clone.
bandwidth. Multicast protocol delivers a singles message to multiple machines. One packet
Features of UDP: from the source is replicated and sent to the destination. Every multicast message 3.Explain the skeleton and stub role in RMI.
1.Provides connectionless, unreliable service. requires a multi case group. The group defines the addresses which will receive the The RMI (Remote Method Invocation) is an API that provides a mechanism to
2.So UDP faster than TCP. message. The group is defined by the class D address. Different routing protocols create distributed application in java.
It provides remote communication between the applications using two objects stub } BufferedReader br = new BufferedReader(new
and skeleton. InputStreamReader(System.in));
Stub static void displayInterfaceInformation(NetworkInterface netint) throws String str = "";
The stub is an object, acts as a gateway for the client side. All the outgoing requests SocketException { String str1 = "";
are routed through it. out.printf("Display name: %s\n", netint.getDisplayName()); while (!str1.equals("stop")) {
It resides at the client side and represents the remote object. When the caller out.printf("Name: %s\n", netint.getName()); str = din.readUTF();//reading reply of client
invokes method on the stub object, it does the following tasks:
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); System.out.println("Devaki's Client Says: " + str);
It initiates a connection with remote Virtual Machine (JVM),
for (InetAddress inetAddress : Collections.list(inetAddresses)) { str1 = br.readLine();
It writes and transmits (marshals) the parameters to the remote Virtual Machine
(JVM), out.printf("InetAddress: %s\n", inetAddress); dos.writeUTF(str1);//sending the reply
It waits for the result } }
It reads (un-marshals) the return value or exception, and out.printf("\n"); s.close();
It finally, returns the value to the caller. } ss.close();
} }
}
Skeleton
The skeleton is an object, acts as a gateway for the server-side object. All the //no.4 client using TCP
incoming requests are routed through it. package Np;
When the skeleton receives the incoming request, it does the following tasks:
It reads the parameter for the remote method
import java.io.*;
It invokes the method on the actual remote object, and
import java.net.Socket;
It writes and transmits (marshals) the result to the caller.

4.Explain RMI architecture. public class socketclient_no4 {

public static void main(String[] args) throws IOException {


In an RMI application, we write two programs, a server program (resides on the ===========================no 2============================ Socket s = new Socket("localhost", 1234);
server) and a client program (resides on the client). 2. Write a Java program to extract raw HTML codes from a URL.
Inside the server program, a remote object is created, and reference of that object
DataInputStream din = new DataInputStream(s.getInputStream());
is made available for the client (using the registry).
package Np; DataOutputStream dos = new DataOutputStream(s.getOutputStream());
The client program requests the remote objects on the server and tries to invoke its
methods.
import java.io.*; BufferedReader br = new BufferedReader(new
import java.util.*; InputStreamReader(System.in));
import java.net.URL; String str = "";
public class urlExtract_02 { String str1 = "";
while (!str1.equals("stop")) {
public static void main(String[] args) str = br.readLine();
throws FileNotFoundException dos.writeUTF(str);
{ str1 = din.readUTF();
try { System.out.println("@Devaki's Server says: " + str1);
URL url = new URL("https://bmc.edu.np"); }
s.close();
BufferedReader br = new BufferedReader(new }
InputStreamReader(url.openStream())); }
1.Transport Layer − This layer connects the client and the server. It manages the System.out.println("Content of website"); =============================no 5=====================
existing connection and sets up new connections. while ((br.readLine()) != null) { 5. Write Java programs for implementing client server communication using UDP.
2.Stub − A stub is a representation (proxy) of the remote object at client. It resides
System.out.println(br.readLine()); import java.io.IOException;
in the client system; it acts as a gateway for the client program.
3.Skeleton − This is the object which resides on the server side. stub communicates } import java.net.DatagramPacket;
with this skeleton to pass request to the remote object. br.close(); import java.net.DatagramSocket;
4.RRL (Remote Reference Layer) − It is the layer which manages the references } import java.net.InetAddress;
made by the client to the remote object. catch (Exception ex) { import java.util.Scanner;

Working of an RMI Application System.out.println(ex.getMessage()); public class udpBaseClient_2


1.When the client makes a call to the remote object, it is received by the stub } {
which eventually passes this request to the RRL.
} public static void main(String args[]) throws IOException
2.When the client-side RRL receives the request, it invokes a method called invoke
() of the object remoteRef. It passes the request to the RRL on the server side. } {
3.The RRL on the server side passes the request to the Skeleton (proxy on the ============================no 3============================ Scanner sc = new Scanner(System.in);
server) which finally invokes the required object on the server. 3. Write a Java program to download a web page.
4.The result is passed all the way back to the client. DatagramSocket ds = new DatagramSocket();
package Np;
5.Explain marshaling and un-marshaling. InetAddress ip = InetAddress.getLocalHost();
Whenever a client invokes a method that accepts parameters on a remote object, import java.io.BufferedReader; byte buf[] = null;
the parameters are bundled into a message before being sent over the network. import java.io.BufferedWriter; while (true)
These parameters may be of primitive type or objects. In case of primitive type, the import java.io.FileWriter; {
parameters are put together and a header is attached to it. In case the parameters import java.io.IOException; String inp = sc.nextLine();
are objects, then they are serialized. This process is known as marshalling.
import java.io.InputStreamReader;
At the server side, the packed parameters are unbundled and then the required
import java.net.URL; buf = inp.getBytes();
method is invoked. This process is known as unmarshalling.

6.Explain the various methods of registering and gaining access to the remote public class webpage_03 { DatagramPacket DpSend =
object. public static void main(String args[]) throws IOException { new DatagramPacket(buf, buf.length, ip, 1234);
The PurseApplet constructor contains the initialization code for the remote object. download("http://www.google.com");
a.First, a javacard. framework. service. RMIService object must be allocated. This } ds.send(DpSend);
service is an object that knows how to handle all the incoming APDU commands public static void download(String urlString) throws IOException {
related to the Java Card RMI protocol. The service must be initialized to allow URL url = new URL(urlString); if (inp.equals("bye"))
remote methods on an instance of the PurseImpl class. A new instance try( break;
of PurseImpl is created and is specified as the initial reference parameter to BufferedReader reader = new BufferedReader(new }
the RMIService constructor as shown in the following code snippet. The initial InputStreamReader(url.openStream())); }
reference is the reference that is made public by an applet to all its clients. It is BufferedWriter writer = new BufferedWriter(new FileWriter("page.html")); }
used as a bootstrap for a client session and is similar to that registered by a Java
){
RMI server to the Java Card RMI registry.
RemoteService rmi = new RMIService (new PurseImpl()); String line; ============================= no6 ==========================
while ((line = reader.readLine()) != null) { 6. Write Java programs for entering two numbers from client and calculate
b.Then, a dispatcher is created and initialized. A dispatcher is the glue among writer.write(line); sum from the server class to display using RMI.
several services. In this example, the initialization is quite simple, because there is a }
single service to initialize: System.out.println("Page downloaded."); package lab_exam;
dispatcher = new Dispatcher((short)1); }
dispatcher. addService (rmi, Dispatcher.PROCESS_COMMAND); } import java.rmi.Remote;
} import java.rmi.RemoteException;
c.Finally, the applet must register itself to the Java Card RE to be made selectable.
This is done in the install method, where the applet constructor is invoked and ============================no4-========================== public interface Sum extends Remote {
immediately registered: 4. Write Java programs for implementing connection-oriented Iterative Service to public int addNum(int a, int b) throws RemoteException;
(new PurseApplet ()). register ();
communicate client and server using TCP.
}
Programs
//no 4 TCP
1. Write a Java program to display all the network interfaces of your PC.
package Np; ---------------------------------------------------------------------------------
import java.io.*; package Np;
import java.io.*;
import java.net.ServerSocket;
import java.net.*;
import java.net.Socket; import java.rmi.RemoteException;
import java.util.*;
public class socketserver_no4 { import java.rmi.server.UnicastRemoteObject;
import static java.lang.System.out;
public static void main(String[] args) throws IOException { import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class ListNets {
ServerSocket ss = new ServerSocket(1234);//step-1 import lab_exam.Sum;
Socket s = ss.accept();
public static void main(String args[]) throws SocketException {
DataInputStream din = new DataInputStream(s.getInputStream()); public class RMIServer extends UnicastRemoteObject implements Sum {
Enumeration<NetworkInterface> nets =
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
NetworkInterface.getNetworkInterfaces();
RMIServer() throws RemoteException {
for (NetworkInterface netint : Collections.list(nets))
super();
displayInterfaceInformation(netint);
}

public int addNum(int x, int y) {


return x + y;
}
public static void main(String args[]) {
try {
Registry reg = LocateRegistry.createRegistry(5000);
reg.rebind("Hi Server", new RMIServer());
System.out.println("Server is ready ...");
} catch (Exception e) {
System.out.println(e);
}
}
}
---------------------------------------------------------------------------
package Np;
import java.rmi.RemoteException;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.Scanner;
import lab_exam.Sum;

public class RmiClient {

public static void main(String args[]) throws RemoteException {


RmiClient c = new RmiClient();
c.connectRemote();
}
private void connectRemote() throws RemoteException {
try {
Registry reg = LocateRegistry.getRegistry("localhost", 5000);
Sum ad = (Sum) reg.lookup("Hi Server");

Scanner sc = new Scanner(System.in);


System.out.println("Enter First Number");
int a = sc.nextInt();
System.out.println("Enter Second Number");
int b = sc.nextInt();

System.out.println("Addition: " + ad.addNum(a, b));


} catch (NotBoundException | RemoteException e) {
System.out.println(e);
}
}
}

================================no 7======================

7. Write a Java program to demonstrate non-blocking I/O.

package Np;

import java.io.*;
import java.nio.*;
import java.nio.channels.FileChannel;

public class nonblockingIO_o7 {

public static void main(String[] args) throws IOException {


FileOutputStream fout = new FileOutputStream("D:\\BCA1\\6th sem\\lab-
np.txt");
FileChannel writeChannel = fout.getChannel();
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
String message = "Write Devaki's file in text file";
writeBuffer.put(message.getBytes());
writeBuffer.flip();
writeChannel.write(writeBuffer);
System.out.println("data written");

FileInputStream fin = new FileInputStream("D:\\BCA1\\6th sem\\lab-np.txt");


<eauta location ma file banau txt ko aani tehi path rakha>
FileChannel readChannel = fin.getChannel();
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
int result = readChannel.read(readBuffer);

while (result > 0) {


readBuffer.flip();
while (readBuffer.hasRemaining()) {
System.out.print((char) readBuffer.get());
}
System.out.println("");
break;
}
fin.close();

}
}

You might also like