SlideShare a Scribd company logo
Advanced Programming
/
Java Programming
By Melese E.
1
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Advanced Programming
/
Java Programming
Networking in Java
2
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Overview
• Socket (Berkeley socket) – identifies an endpoint in a network
• Sockets are at the foundation of modern networking because a socket allows a single computer to
serve many different clients at once, as well as to serve many different types of information
• This is accomplished through the use of a port, which is a numbered socket on a particular machine.
• A server process is said to "listen" to a port until a client connects to it.
• A server is allowed to accept multiple clients connected to the same port number, although each session is
unique.
• To manage multiple client connections, a server process must be multithreaded or have some other means of multiplexing the
simultaneous I/O
• Socket communication takes place via a protocol.
• Internet Protocol (IP) is a low-level routing protocol that breaks data into small packets and sends them to an
address across a network, which does not guarantee to deliver said packets to the destination.
• Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string together these
packets, sorting and retransmitting them as necessary to reliably transmit data.
• A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast,
connectionless, unreliable transport of packets
• The application layer is identified by the use of ports
• TCP/IP reserves the lower 1,024 ports for specific protocols.
• A few might be familiar to you. For example, port number 21 is for FTP; 23 is for Telnet; 25 is for e-mail; 43 is for whois; 80 is for
HTTP; 119 is for netnews.
3
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Overview
• A key component of the Internet (or networking in generals) is the address.
• Every computer on the Internet has one.
• An Internet address is a number that uniquely identifies each computer on the Net
• IPv4 address – 32 bit
• IPv6 address – 128 bit
• Just as the numbers of an IP address describe a network hierarchy, the name of an Internet
address, called its domain name, describes a machine’s location in a name space
• For example, www.google.com
• Domain names are human readable
• But, the computer uses IP addresses to uniquely identify devices
• DNS (Domain Name System) – is an application layer protocol which is in charge of converting
domain names into IP address and vice versa
• In Java, you can develop network applications
• Using TCP – connection-oriented reliable transport layer protocol
• Using UDP – connectionless unreliable transport layer protocol
• Using RMI – the ability to call a method on a remote computer
• Java’s networking related classes are defined in the java.net package
• Beginning with JDK 11, Java has also provided enhanced networking support for HTTP clients in
the java.net.http package
4
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Socket Programming
Networking in Java – Socket Programming
• Socket – IP address + Port
• IP address – identifies the device (computer)
• Port – identifies the application on the device
• 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
5
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Socket Programming
• The client – using TCP socket
• 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
• The two constructors of the Socket class are
• Socket(String hostName, int port) throws UnknownHostException, IOException – Creates a socket
connected to the named host and port
• Socket(InetAddress ipAddress, int port) throws IOException – Creates a socket using a preexisting
InetAddress object and a port
• Some of the methods of Socket instance are
• InetAddress getInetAddress( ) – Returns the InetAddress associated with the Socket object. It returns null
if the socket is not connected
• int getPort() – Returns the remote port to which the invoking Socket object is connected. It returns 0 if
the socket is not connected
• int getLocalPort() – Returns the local port to which the invoking Socket object is bound. It returns –1 if
the socket is not bound
• InputStream getInputStream( ) throws IOException – Returns s the InputStream associated with the
invoking socket
• OutputStream getOutputStream( ) throws IOException – Returns the OutputStream associated with the
invoking socket
• void close() – closes the connection
6
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Socket Programming
import java.net.*;
import java.io.*;
public class ClientSocket {
public static void main(String[] args)throws Exception{
Socket soc = new Socket("localhost", 5000);
InputStream in = soc.getInputStream(); //byte oriented
OutputStream out = soc.getOutputStream(); //byte oriented
//You can attach these io objects to other streams
BufferedReader br = new BufferedReader(new InputStreamReader(in)); //character oriented
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); //character oriented
bw.write("message for the server");
int c;
while((c = br.read()) != -1){
System.out.println((char)c);
}
soc.close();
}
}
7
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Socket Programming
• The Server – using TCP socket
• 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 client 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 constructors of the ServerSocket class
• ServerSocket(int port) throws IOException – Creates server socket on the specified port
with a queue length of 50
• ServerSocket(int port, int maxQueue) throws IOException – Creates a server socket on
the specified port with a maximum queue length of maxQueue
• The methods
• Socket 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
8
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Socket Programming
import java.net.*;
import java.io.*;
public class TheServer {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(50001);
Socket soc = ss.accept();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream()));
System.out.println(soc.getPort());
bw.write("This is a message from the server");
bw.flush();
int a;
while((a=br.read()) != -1){
System.out.print((char)a);
}
soc.close();
}
}
9
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Socket Programming
10
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Socket Programming
• Some important classes of the java.net package
• InetAddress class – used to work with IPv4 / IPv6 addresses – uses factory
methods to create an object of InetAddress
• URL class – used to create Uniform Resource Locator (URL)
• DatagramSocket – to work with UDP
• DatagramPacket – to work with UDP
• URLConnection – to get connected to a specified URL and analyze the
connection
• UnknownHostException – an exception thrown when trying to connect to an
unknown server
• MalformedURLException – an exception thrown when the string representing
the URL is incorrect
11
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Remote Method Invocation
• Remote Method Invocation (RMI) allows a Java object that executes
on one machine to invoke a method of a Java object that executes on
another machine
• This is an important feature, because it allows you to build distributed
applications
• The java.rmi package contains classes for creating RMI applications –
some of the important ones are
• Remote interface
• Naming class
• RemoteException and NotBoundException classes
• The java.rmi.server package provides classes for creating an RMI
server – the important one is
• UnicastRemoteObject class
• The MalformedURLException from java.net package is also important
12
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Remote Method Invocation
• Steps in creating RMI Server and Client
• Step One: Create an interface that extends the Remote interface
• This interface specifies the methods that are going to be called by the client
• The methods throws RemoteException
• Step Two: Create an implementation of the interface created in step one
• This implementation class must be a subclass of UnicastRemoteObject and must implement
the interface of step one
• All the methods specified in the interface must be implemented
• Should have at least a default constructor that throws RemoteException
• Step Three: Create a class containing the main method
• In the main method
• Create an object of the implementation of step one
• Register this object into the rmi registry of the server
• Step Four: Create the client
• Copy the interface defined in step one and put it in the folder where the client application is
saved
• Create a class containing the main method – and in the main method do the following
• Declare a reference variable of the interface defined in step one
• Search for the registered object
• Assign the search result to the reference variable created
13
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Remote Method Invocation
• To run and test the application
• Compile all the files
• Then, being on the server directory, start the rmi registry of the server using
the following command
• start rmiregistry
• Run the server
• Then run the client
• The interface
import java.rmi.*; //Remote and RemoteException classes
public interface ServerInterface extends Remote{
public double add(double x, double y) throws RemoteException;
}
14
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Remote Method Invocation
• The implementation of the interface
import java.rmi.*;//RemoteException
import java.rmi.server.*;//UnicastRemoteObject
public class ServerImplementation extends UnicastRemoteObject implements ServerInterface{
public ServerImplementation() throws RemoteException{
}
public double add(double x, double y) throws RemoteException{
return x + y;
}
}
15
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Remote Method Invocation
• The Server Application
import java.rmi.*;//Naming and RemoteException
import java.net.*; //for MalformedURLException
public class ServerMain {
public static void main(String[] args) {
try{
ServerImplementation si = new ServerImplementation();
Naming.rebind("addition", si); // registering the object in the rmi registry
}catch(MalformedURLException e){
}catch(RemoteException e){
}
}
}
16
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
Networking in Java – Remote Method Invocation
• The Client Applciation
import java.rmi.*;//Naming, NotBoundException and RemoteException
import java.net.*;//MalformedURLException
public class RMIClient {
public static void main(String[] args){
String serverURL = "rmi://localhost/addition";
try{
ServerInterface si = (ServerInterface)Naming.lookup(serverURL);
double x = 55.5, y = 157.2;
double sum = si.add(x, y);
System.out.println("The sum is " + sum);
}catch(MalformedURLException e){
}
catch(NotBoundException e){
}
catch(RemoteException e){
}
}
}
17
By Melese E., Department of Computer Science
Wednesday, May 29, 2024
The End!
18
By Melese E., Department of Computer Science
Wednesday, May 29, 2024

More Related Content

PPTX
5_6278455688045789623.pptx
EliasPetros
 
PDF
Java networking programs - theory
Mukesh Tekwani
 
PDF
28 networking
Ravindra Rathore
 
PPTX
Socket & Server Socket
Hemant Chetwani
 
PPT
Basic Networking in Java
suraj pandey
 
PDF
04 android
guru472
 
PDF
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
DOCX
Mail Server Project Report
Kavita Sharma
 
5_6278455688045789623.pptx
EliasPetros
 
Java networking programs - theory
Mukesh Tekwani
 
28 networking
Ravindra Rathore
 
Socket & Server Socket
Hemant Chetwani
 
Basic Networking in Java
suraj pandey
 
04 android
guru472
 
Chap 1 Network Theory & Java Overview
Ministry of Higher Education
 
Mail Server Project Report
Kavita Sharma
 

Similar to Unit 6 - Netwohhhhhddddrking in Java.pdf (20)

PPTX
Java socket programming
Mohammed Abdalla Youssif
 
PPTX
Java seminar.pptx
shirindigitel
 
PPTX
OOP Lecture 24-Network Programming-Part1.pptx
Tanzila Kehkashan
 
PPT
Multi user chat system using java
Akhil Goutham Kotini
 
PPT
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Abodahab
 
PPT
java networking
Waheed Warraich
 
PPTX
Client server chat application
Piyush Rawat
 
PPT
Socket Programming - nitish nagar
Nitish Nagar
 
PDF
Network Programming Clients
Adil Jafri
 
PDF
15network Programming Clients
Adil Jafri
 
PPT
Java networking
Arati Gadgil
 
PPTX
Java networking
ssuser3a47cb
 
PPTX
Java 1
VidyaVarshini3
 
PPTX
A.java
JahnaviBhagat
 
PPT
Sockets
sivindia
 
PDF
17-Networking.pdf
sophia763824
 
PPTX
Java
kasthurimukila
 
PPT
Network programming in Java
Tushar B Kute
 
PPT
Socket Programming
leminhvuong
 
PPTX
Chapter 4
Ebisa Bekele
 
Java socket programming
Mohammed Abdalla Youssif
 
Java seminar.pptx
shirindigitel
 
OOP Lecture 24-Network Programming-Part1.pptx
Tanzila Kehkashan
 
Multi user chat system using java
Akhil Goutham Kotini
 
Sockets.ppt socket sofcv ohghjagshsdjjhjfb
Abodahab
 
java networking
Waheed Warraich
 
Client server chat application
Piyush Rawat
 
Socket Programming - nitish nagar
Nitish Nagar
 
Network Programming Clients
Adil Jafri
 
15network Programming Clients
Adil Jafri
 
Java networking
Arati Gadgil
 
Java networking
ssuser3a47cb
 
Sockets
sivindia
 
17-Networking.pdf
sophia763824
 
Network programming in Java
Tushar B Kute
 
Socket Programming
leminhvuong
 
Chapter 4
Ebisa Bekele
 
Ad

Recently uploaded (20)

PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPT
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
PDF
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
PPTX
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PDF
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Doc9.....................................
SofiaCollazos
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
L2 Rules of Netiquette in Empowerment technology
Archibal2
 
Best ERP System for Manufacturing in India | Elite Mindz
Elite Mindz
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
CIFDAQ'S Market Insight: BTC to ETH money in motion
CIFDAQ
 
Stamford - Community User Group Leaders_ Agentblazer Status, AI Sustainabilit...
Amol Dixit
 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Chapter 1 Introduction to CV and IP Lecture Note.pdf
Getnet Tigabie Askale -(GM)
 
Software Development Company | KodekX
KodekX
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Doc9.....................................
SofiaCollazos
 
Ad

Unit 6 - Netwohhhhhddddrking in Java.pdf

  • 1. Advanced Programming / Java Programming By Melese E. 1 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 2. Advanced Programming / Java Programming Networking in Java 2 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 3. Networking in Java – Overview • Socket (Berkeley socket) – identifies an endpoint in a network • Sockets are at the foundation of modern networking because a socket allows a single computer to serve many different clients at once, as well as to serve many different types of information • This is accomplished through the use of a port, which is a numbered socket on a particular machine. • A server process is said to "listen" to a port until a client connects to it. • A server is allowed to accept multiple clients connected to the same port number, although each session is unique. • To manage multiple client connections, a server process must be multithreaded or have some other means of multiplexing the simultaneous I/O • Socket communication takes place via a protocol. • Internet Protocol (IP) is a low-level routing protocol that breaks data into small packets and sends them to an address across a network, which does not guarantee to deliver said packets to the destination. • Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string together these packets, sorting and retransmitting them as necessary to reliably transmit data. • A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast, connectionless, unreliable transport of packets • The application layer is identified by the use of ports • TCP/IP reserves the lower 1,024 ports for specific protocols. • A few might be familiar to you. For example, port number 21 is for FTP; 23 is for Telnet; 25 is for e-mail; 43 is for whois; 80 is for HTTP; 119 is for netnews. 3 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 4. Networking in Java – Overview • A key component of the Internet (or networking in generals) is the address. • Every computer on the Internet has one. • An Internet address is a number that uniquely identifies each computer on the Net • IPv4 address – 32 bit • IPv6 address – 128 bit • Just as the numbers of an IP address describe a network hierarchy, the name of an Internet address, called its domain name, describes a machine’s location in a name space • For example, www.google.com • Domain names are human readable • But, the computer uses IP addresses to uniquely identify devices • DNS (Domain Name System) – is an application layer protocol which is in charge of converting domain names into IP address and vice versa • In Java, you can develop network applications • Using TCP – connection-oriented reliable transport layer protocol • Using UDP – connectionless unreliable transport layer protocol • Using RMI – the ability to call a method on a remote computer • Java’s networking related classes are defined in the java.net package • Beginning with JDK 11, Java has also provided enhanced networking support for HTTP clients in the java.net.http package 4 By Melese E., Department of Computer Science Wednesday, May 29, 2024 Socket Programming
  • 5. Networking in Java – Socket Programming • Socket – IP address + Port • IP address – identifies the device (computer) • Port – identifies the application on the device • 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 5 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 6. Networking in Java – Socket Programming • The client – using TCP socket • 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 • The two constructors of the Socket class are • Socket(String hostName, int port) throws UnknownHostException, IOException – Creates a socket connected to the named host and port • Socket(InetAddress ipAddress, int port) throws IOException – Creates a socket using a preexisting InetAddress object and a port • Some of the methods of Socket instance are • InetAddress getInetAddress( ) – Returns the InetAddress associated with the Socket object. It returns null if the socket is not connected • int getPort() – Returns the remote port to which the invoking Socket object is connected. It returns 0 if the socket is not connected • int getLocalPort() – Returns the local port to which the invoking Socket object is bound. It returns –1 if the socket is not bound • InputStream getInputStream( ) throws IOException – Returns s the InputStream associated with the invoking socket • OutputStream getOutputStream( ) throws IOException – Returns the OutputStream associated with the invoking socket • void close() – closes the connection 6 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 7. Networking in Java – Socket Programming import java.net.*; import java.io.*; public class ClientSocket { public static void main(String[] args)throws Exception{ Socket soc = new Socket("localhost", 5000); InputStream in = soc.getInputStream(); //byte oriented OutputStream out = soc.getOutputStream(); //byte oriented //You can attach these io objects to other streams BufferedReader br = new BufferedReader(new InputStreamReader(in)); //character oriented BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out)); //character oriented bw.write("message for the server"); int c; while((c = br.read()) != -1){ System.out.println((char)c); } soc.close(); } } 7 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 8. Networking in Java – Socket Programming • The Server – using TCP socket • 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 client 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 constructors of the ServerSocket class • ServerSocket(int port) throws IOException – Creates server socket on the specified port with a queue length of 50 • ServerSocket(int port, int maxQueue) throws IOException – Creates a server socket on the specified port with a maximum queue length of maxQueue • The methods • Socket 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 8 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 9. Networking in Java – Socket Programming import java.net.*; import java.io.*; public class TheServer { public static void main(String[] args) throws Exception{ ServerSocket ss = new ServerSocket(50001); Socket soc = ss.accept(); BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(soc.getOutputStream())); BufferedReader br = new BufferedReader(new InputStreamReader(soc.getInputStream())); System.out.println(soc.getPort()); bw.write("This is a message from the server"); bw.flush(); int a; while((a=br.read()) != -1){ System.out.print((char)a); } soc.close(); } } 9 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 10. Networking in Java – Socket Programming 10 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 11. Networking in Java – Socket Programming • Some important classes of the java.net package • InetAddress class – used to work with IPv4 / IPv6 addresses – uses factory methods to create an object of InetAddress • URL class – used to create Uniform Resource Locator (URL) • DatagramSocket – to work with UDP • DatagramPacket – to work with UDP • URLConnection – to get connected to a specified URL and analyze the connection • UnknownHostException – an exception thrown when trying to connect to an unknown server • MalformedURLException – an exception thrown when the string representing the URL is incorrect 11 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 12. Networking in Java – Remote Method Invocation • Remote Method Invocation (RMI) allows a Java object that executes on one machine to invoke a method of a Java object that executes on another machine • This is an important feature, because it allows you to build distributed applications • The java.rmi package contains classes for creating RMI applications – some of the important ones are • Remote interface • Naming class • RemoteException and NotBoundException classes • The java.rmi.server package provides classes for creating an RMI server – the important one is • UnicastRemoteObject class • The MalformedURLException from java.net package is also important 12 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 13. Networking in Java – Remote Method Invocation • Steps in creating RMI Server and Client • Step One: Create an interface that extends the Remote interface • This interface specifies the methods that are going to be called by the client • The methods throws RemoteException • Step Two: Create an implementation of the interface created in step one • This implementation class must be a subclass of UnicastRemoteObject and must implement the interface of step one • All the methods specified in the interface must be implemented • Should have at least a default constructor that throws RemoteException • Step Three: Create a class containing the main method • In the main method • Create an object of the implementation of step one • Register this object into the rmi registry of the server • Step Four: Create the client • Copy the interface defined in step one and put it in the folder where the client application is saved • Create a class containing the main method – and in the main method do the following • Declare a reference variable of the interface defined in step one • Search for the registered object • Assign the search result to the reference variable created 13 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 14. Networking in Java – Remote Method Invocation • To run and test the application • Compile all the files • Then, being on the server directory, start the rmi registry of the server using the following command • start rmiregistry • Run the server • Then run the client • The interface import java.rmi.*; //Remote and RemoteException classes public interface ServerInterface extends Remote{ public double add(double x, double y) throws RemoteException; } 14 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 15. Networking in Java – Remote Method Invocation • The implementation of the interface import java.rmi.*;//RemoteException import java.rmi.server.*;//UnicastRemoteObject public class ServerImplementation extends UnicastRemoteObject implements ServerInterface{ public ServerImplementation() throws RemoteException{ } public double add(double x, double y) throws RemoteException{ return x + y; } } 15 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 16. Networking in Java – Remote Method Invocation • The Server Application import java.rmi.*;//Naming and RemoteException import java.net.*; //for MalformedURLException public class ServerMain { public static void main(String[] args) { try{ ServerImplementation si = new ServerImplementation(); Naming.rebind("addition", si); // registering the object in the rmi registry }catch(MalformedURLException e){ }catch(RemoteException e){ } } } 16 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 17. Networking in Java – Remote Method Invocation • The Client Applciation import java.rmi.*;//Naming, NotBoundException and RemoteException import java.net.*;//MalformedURLException public class RMIClient { public static void main(String[] args){ String serverURL = "rmi://localhost/addition"; try{ ServerInterface si = (ServerInterface)Naming.lookup(serverURL); double x = 55.5, y = 157.2; double sum = si.add(x, y); System.out.println("The sum is " + sum); }catch(MalformedURLException e){ } catch(NotBoundException e){ } catch(RemoteException e){ } } } 17 By Melese E., Department of Computer Science Wednesday, May 29, 2024
  • 18. The End! 18 By Melese E., Department of Computer Science Wednesday, May 29, 2024