Advanced Programming Java-H-U4

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

AMBO UNIVERSITY WOLISO CAMPUS

School of Technology and Informatics Department of Information Technology


Course Title: Advanced Programming in Java Course Code: ITec3058, ECTS: 5
Unit Four: Network Programming
4.1 Introduction to Socket Programming
The Java API provides the classes for creating sockets to facilitate program communications over the Internet.
Socket
Sockets are the endpoints of logical connections between two hosts and can be used to send and receive data.
Java treats socket communications much as it treats I/O operations; thus, programs can read from or write to
sockets as easily as they can read from or write to files. Network programming usually involves a server and
one or more clients. The client sends requests to the server, and the server responds. The client begins by
attempting to establish a connection to the server. The server can accept or deny the connection. Once a
connection is established, the client and the server communicate through sockets.
The server must be running when a client attempts to connect to the server. The server waits for a connection
request from the client. The statements needed to create sockets on a server and on a client are shown below.
Server Socket
Server Sockets to establish a server, you need to create a server socket and attach it to a port, which is where
the server listens for connections. The port identifies the TCP service on the socket. Port numbers range from
0 to 65536, but port numbers 0 to 1024 are reserved for privileged services.

Figure 4.1: The server creates a server socket and, once a connection to a client is established, connects to
the client with a client socket.
A socket is one of the most fundamental technologies of computer network programming. It is a way of
connecting two nodes on a network to communicate with each other. Socket-based software usually runs on
two separate computers on the network, but sockets can also be used to communicate locally (interprocess) on
a single computer.
The Java Socket Programming has two sections.
▪ Java Server Socket Program
▪ Java Client Socket Program

Advanced Programming in Java Lecture notes by: Jerusalem F 1


Java Server Socket Program
The Server Socket Program here is a Java Console based Application. This program act as a Server and
listening to clients request from Port No.1357.

The next step is to create an infinite loop for monitoring the request from client side and replying from server
side. When the Server Socket accept a request from the client side, it reads the data from DataInputStream
and also it writes the response to DataOutputStream.
Server Socket Example/Program

Java Client Socket Program


The Client is connected to the Port 1357 of the Java Server Socket Program, and the IP Address (Computer
Name) of the server machine. Here we give as 127.0.0.1, because the Server and Client running on the same
machine. If the client program running on other machine, then you can give the IP Address of that machine.

Advanced Programming in Java Lecture notes by: Jerusalem F 2


When the Java Client program starts, it will connect to the Java Server Socket Program and waiting input
from client side. When you type the message, it will send to the server and then you can see the reply messages
from server side too.
Socket Client Example

How to run this program?


When you finish coding and compiled the Server and Client program, first you have to start Java Server Socket
Program from DOS prompt (console), then you will get a message " Server Started..." in your DOS screen,
where the server program is running.
Next step is to start Java Client Socket Program in the same computer or other computers on the same
network. When you start the client program, it will establish a connection to the Server and waiting input from
client side. When you type the message and press ENTER button, then you can see the same message on server
side. After receiving message from client side, you can send message to client from server side. When the
client sends "bye" from client side the server closes the connection from client.
Output
Advanced Programming in Java Lecture notes by: Jerusalem F 3
Some applications of Network Programming
1) to find IP address and computer/host name
The InetAddress class can be used to perform Domain Name Server (DNS) lookups. The host name can
either be a machine name, such as "mail.yahoo.com", or a textual representation of its IP address. The
java.net.InetAddress class provides methods to get the IP of any host name for example www.yahoo.com,
www.facebook.com etc.
InetAddress has no public constructor, so you must obtain instances via a set of static methods.

Java InetAddress Class is used to encapsulate the two things.


▪ Numeric IP Address
▪ The domain name for that address
1) getLocalHost(): getLocalHost method returns the InetAddress object that represents the local host contain
the name and address both. If this method unable to find out the host name, it throws an
UnknownHostException.

2) getByName(): getByName method returns an InetAddress for a host name passed to it as a parameter
argument. If this method unable to find out the host name, it throws an UnknownHostException.

Example

Advanced Programming in Java Lecture notes by: Jerusalem F 4


Output

2) to get URL content


Reading from a URL is as easy as reading from an input stream. URL is the acronym for Uniform Resource
Locator. Java programs that interact with the Internet also may use URLs to find the resources on the Internet
they wish to access. Java programs can use a class called URL in the java.net package to represent a URL
address. A URL takes the form of a string that describes how to find a resource on the Internet. URLs have
two main components: the protocol needed to access the resource and the location of the resource. The easiest
way to create a URL object is from a String that represents the human-readable form of the URL address.

Steps for reading URL Content from webserver:


▪ Create a URL object from the String representation.
▪ Create a new BufferedReader, using a new InputStreamReader with the URL input stream.
▪ Read the text, using readLine() API method of BufferedReader.
Example

Advanced Programming in Java Lecture notes by: Jerusalem F 5


Output

4.2 Remote Method Invocation


RMI is a way that a programmer, using the Java programming language and development environment, can
write object-oriented programming in which objects on different computers can interact in a distributed
network.
RMI is a pure java solution to Remote Procedure Calls (RPC) and is used to create distributed application in
java. Stub and Skeleton objects are used for communication between client and server side.
It is an API which allows an object to invoke a method on an object that exists in another address space, which
could be on the same machine or on a remote machine. Through RMI, object running in a JVM present on a
computer (Client side) can invoke methods on an object present in another JVM (Server side). RMI creates a
public remote server object that enables client and server-side communications through simple method calls
on the server object.
Working of RMI
The communication between client and server is handled by using two intermediate objects: Stub object (on c
lient side) and Skeleton object (on server side).
Stub Object

Advanced Programming in Java Lecture notes by: Jerusalem F 6


The stub object on the client machine builds an information block and sends this information to the server. T
he block consists of
• An identifier of the remote object to be used
• Method name which is to be invoked
• Parameters to the remote JVM
Skeleton Object
The skeleton object passes the request from the stub object to the remote object. It performs following tasks
• It calls the desired method on the real object present on the server.
• It forwards the parameters received from the stub object to the method.
Steps to implement Interface
1. Defining a remote interface
2. Implementing the remote interface
3. Creating Stub and Skeleton objects from the implementation class using rmic (rmi complier)
4. Start the rmiregistry
5. Create and execute the server application program
6. Create and execute the client application program.
Working with RMI
1. Interface program
2. Implementation program
3. Server program
4. Client program
RMI Example1: Calculating the factorial of a given number using the RMI concept.
Step 1: Interface Program
Declare the Methods only.
Open the first note pad, type the following program, and save the file as “rint.java”.
Interface Program (RMIInterface.java)

1. import java.rmi.*;
2. public interface rint extends Remote {
3. double fact(double x) throws RemoteException;
4. }
Step 2: Implementation Program
Define Methods only.
Open the second note pad, type the following program, and save the file as “rimp.java”.

Advanced Programming in Java Lecture notes by: Jerusalem F 7


Implementation Program (rimp.java)
1. import java.rmi.*;
2. import java.rmi.server.*;
3. public class rimp extends UnicastRemoteObject implements rint {
4. public rimp() throws RemoteException {}
5. public double fact(double x) throws RemoteException {
6. if (x <= 1) return (1);
7. else return (x * fact(x - 1));
8. }
9. }
Step 3: Server Program
It is the main program.
Open the third note pad, type the following program, and save the file as “rser.java”.
Server Program (rser.java)
1. import java.rmi.*;
2. import java.net.*;
3. public class rser {
4. public static void main(String arg[]) {
5. try {
6. rimp ri = new rimp();
7. Naming.rebind("rser", ri);
8. } catch (Exception e) {
9. System.out.println(e);
10. }
11. }
12. }
Step 4: Client Program
It is the data send (request) to the Server program.
Open the fourth note pad, type the following program, and save the file as “rcli.java”.
Client Program (rcli.java)
1. import java.rmi.*;
2. public class rcli {
3. public static void main(String arg[]) {
4. try {
Advanced Programming in Java Lecture notes by: Jerusalem F 8
5. rint rr = (rint) Naming.lookup("rmi://172.16.13.2/rser");
6. double s = rr.fact(5);
7. System.out.println("Factorial value is… : " + s);
8. } catch (Exception e) {
9. System.out.println(e);
10. }
11. }
12. }
Explanation
Compile and Execute the Program.
In a single system, let us assume that we can open two command prompts. One command prompt is called
Server while the other one is called Client.
RMI Example2
Step 1: Defining the remote interface
The first thing to do is to create an interface which will provide the description of the methods that can be
invoked by remote clients. This interface should extend the Remote interface and the method prototype within
the interface should throw the RemoteException.
// Creating a Search interface
import java.rmi.*;
public interface Search extends Remote
{
// Declaring the method prototype
public String query(String search) throws RemoteException;
}
Step 2: Implementing the remote interface
The next step is to implement the remote interface. To implement the remote interface, the class should extend
to UnicastRemoteObject class of java.rmi package. Also, a default constructor needs to be created to throw the
java.rmi.RemoteException from its parent constructor in class.
// Java program to implement the Search interface
import java.rmi.*;
import java.rmi.server.*;
public class SearchQuery extends UnicastRemoteObject
implements Search
{
Advanced Programming in Java Lecture notes by: Jerusalem F 9
// Default constructor to throw RemoteException
// from its parent constructor
SearchQuery() throws RemoteException
{
super();
}

// Implementation of the query interface


public String query(String search)
throws RemoteException
{
String result;
if (search.equals("Reflection in Java"))
result = "Found";
else
result = "Not Found";

return result;
}
}
Step 3: Creating Stub and Skeleton objects from the implementation class using rmic
The rmic tool is used to invoke the rmi compiler that creates the Stub and Skeleton objects. Its prototype is
rmic classname. For above program the following command need to be executed at the command prompt
rmic SearchQuery
STEP 4: Start the rmiregistry
Start the registry service by issuing the following command at the command prompt start rmiregistry
STEP 5: Create and execute the server application program
The next step is to create the server application program and execute it on a separate command prompt.
The server program uses createRegistry method of LocateRegistry class to create rmiregistry within the server
JVM with the port number passed as argument.
The rebind method of Naming class is used to bind the remote object to the new name.

//program for server application


import java.rmi.*;

Advanced Programming in Java Lecture notes by: Jerusalem F 10


• import java.rmi.registry.*;
• public class SearchServer {
• public static void main(String args[]) {
• try {
• // Create an object of the interface
• // implementation class
• Search obj = new SearchQuery();
• // rmiregistry within the server JVM with
• // port number 1900
• LocateRegistry.createRegistry(1900);
• // Binds the remote object by the name
• // ghionacademy
• Naming.rebind("rmi://localhost:1900"+ "/ ghionacademy ",obj);
• }
• catch(Exception e) {
• System.out.println(e);
• }
• }
• }
Step 6: Create and execute the client application program
The last step is to create the client application program and execute it on a separate command prompt. The
lookup method of Naming class is used to get the reference of the Stub object.
• //program for client application
• import java.rmi.*;
• public class ClientRequest {
• public static void main(String args[]) {
• String answer,value="Reflection in Java";
• try {
• // lookup method to find reference of remote object
• Search access = (Search)Naming.lookup("rmi://localhost:1900"+ "/ghionacademy");
• answer = access.query(value);
• System.out.println("Article on " + value + " " + answer + " at Ghion Academy ");
• }
Advanced Programming in Java Lecture notes by: Jerusalem F 11
• catch(Exception e) {
• System.out.println(e);
• }
• }
• }
Note: The above client and server program is executed on the same machine so localhost is used. In order to
access the remote object from another machine, localhost is to be replaced with the IP address where the remote
object is present.
RMI Example3: a program which displays the sum of two numbers from user by invoking a method Add().
The Remote Interface program

The Server Program

Advanced Programming in Java Lecture notes by: Jerusalem F 12


The client program

Output
First Run the server program and then the client program

Note: While typing or before running the client and server program, add an interface .jar file which is
previously <clean-build> from your current project folder→dist folder

Advanced Programming in Java Lecture notes by: Jerusalem F 13

You might also like