Chapter-Six
Networking in Java
BY:
Andargie Mekonnen
Java Socket Programming
Java Socket programming is used for communication between the applications
running on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.
The client in socket programming must know two information:
IP Address of Server, and
Port number.
7/5/2024 Andargie Mekonnen 2
Java Socket Programming
Here, we are going to make one-way client and server communication. In this
application, client sends a message to the server, server reads the message and prints it.
Here, two classes are being used: Socket and ServerSocket.
The Socket class is used to communicate client and server. Through this class, we can
read and write message.
The ServerSocket class is used at server-side. The accept() method of ServerSocket class
blocks the console until the client is connected.
After the successful connection of client, it returns the instance of Socket at server-side.
7/5/2024 Andargie Mekonnen 3
Java Socket Programming
7/5/2024 Andargie Mekonnen 4
Java Socket Programming
Socket class
A socket is simply an endpoint for communications between the machines. The
Socket class can be used to create a socket.
Important methods
Method Description
1) public InputStream getInputStream() returns the InputStream attached with
this socket.
2)Public OutputStream getOutputStream() returns the OutputStream attached with
this socket.
3) public synchronized void close() closes this socket
7/5/2024 Andargie Mekonnen 5
Java Socket Programming
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to
establish communication with the clients.
Important methods
Method Description
1) public Socket accept() returns the socket and establish a connection
between server and client.
2) public synchronized void close() closes the server socket.
7/5/2024 Andargie Mekonnen 6
Example of Java Socket Programming
Creating Server:
To create the server application, we need to create the instance of ServerSocket class.
Here, we are using 6666 port number for the communication between the client and
server. You may also choose any other port number.
The accept() method waits for the client.
If clients connects with the given port number, it returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s=[Link]();//establishes connection and waits for the client
7/5/2024 Andargie Mekonnen 7
Example of Java Socket Programming
Creating Client:
To create the client application, we need to create the instance of Socket class.
Here, we need to pass the IP address or hostname of the Server and a port number.
Here, we are using "localhost" because our server is running on same system.
Socket s=new Socket("localhost",6666);
.
7/5/2024 Andargie Mekonnen 8
Example of Java Socket Programming
Let's see a simple of Java socket programming Socket s=[Link]();//establishes connection
where client sends a text and server receives and
DataInputStream dis=new
prints it.
DataInputStream([Link]());
File: [Link]
String str=(String)[Link]();
import [Link].*;
[Link]("message= "+str);
import [Link].*;
[Link]();
public class MyServer {
public static void main(String[] args){
}catch(Exception e){[Link](e);}
try{ }
ServerSocket ss=new ServerSocket(6666); }
7/5/2024 Andargie Mekonnen 9
Example of Java Socket Programming
File: [Link] DataOutputStream dout=new
DataOutputStream([Link]());
import [Link].*;
[Link]("Hello Server");
import [Link].*;
[Link]();
public class MyClient {
[Link]();
public static void main(String[] args) { [Link]();
try{ }catch(Exception e){[Link](e);}
Socket s=new Socket("localhost",6666); }
}
7/5/2024 Andargie Mekonnen 10
Example of Java Socket Programming (Read-Write both side)
In this example, client will write first to the server then server will receive and print the text.
Then server will write to the client and client will receive and print the text. The step goes on.
File: [Link]
import [Link].*;
import [Link].*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=[Link]();
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
7/5/2024 Andargie Mekonnen 11
Example of Java Socket Programming (Read-Write both side)
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String str="",str2="";
while(){
str=[Link]();
[Link]("client says: "+str);
str2=[Link]();
[Link](str2);
[Link]();
}
[Link]();
[Link]();
[Link]();
}}
7/5/2024 Andargie Mekonnen 12
Example of Java Socket Programming (Read-Write both side)
File: [Link]
import [Link].*;
import [Link].*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
7/5/2024 Andargie Mekonnen 13
Example of Java Socket Programming (Read-Write both side)
String str="",str2="";
while(){
str=[Link]();
[Link](str);
[Link]();
str2=[Link]();
[Link]("Server says: "+str2);
[Link]();
[Link](); }}
7/5/2024 Andargie Mekonnen 14
RMI (Remote Method Invocation)
The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java.
The RMI allows an object to invoke methods on an object running in another JVM.
The RMI provides remote communication between the applications using two objects
stub and skeleton.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM.
7/5/2024 Andargie Mekonnen 15
RMI (Remote Method Invocation)
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are
routed through it. It resides at the client side and represents the remote object. When the
caller invokes method on the stub object, it does the following tasks:
It initiates a connection with remote Virtual Machine (JVM),
It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
It waits for the result
It reads (unmarshals) the return value or exception, and
It finally, returns the value to the caller.
7/5/2024 Andargie Mekonnen 16
RMI (Remote Method Invocation)
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming
requests are routed through it. When the skeleton receives the incoming request, it does
the following tasks:
It reads the parameter for the remote method
It invokes the method on the actual remote object, and
It writes and transmits (marshals) the result to the caller.
7/5/2024 Andargie Mekonnen 17
RMI (Remote Method Invocation)
7/5/2024 Andargie Mekonnen 18
RMI (Remote Method Invocation)
steps to write the RMI program.
1. Create the remote interface
2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using the
rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application
7/5/2024 Andargie Mekonnen 19
RMI Example
In this example, we have followed all the 6 steps to create and run the rmi application.
The client application need only two files, remote interface and client application.
In the rmi application, both client and server interacts with the remote interface.
The client application invokes methods on the proxy object, RMI sends the request to
the remote JVM.
The return value is sent back to the proxy object and then to the client application.
7/5/2024 Andargie Mekonnen 20
RMI Example
7/5/2024 Andargie Mekonnen 21
RMI Example
Create the remote interface
For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface. Here, we are creating a
remote interface that extends the Remote interface. There is only one method named
add() and it declares RemoteException.
import [Link].*;
public interface Adder extends Remote{
public int add(int x,int y)throws RemoteException;
}
7/5/2024 Andargie Mekonnen 22
RMI Example
Provide the implementation of the remote interface
For providing the implementation of the Remote interface, we need to either extend the
UnicastRemoteObject class, or use the exportObject() method of the UnicastRemoteObject class
In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
import [Link].*;
import [Link].*;
public class AdderRemote extends UnicastRemoteObject implements Adder{
AdderRemote()throws RemoteException{
super(); }
public int add(int x,int y){return x+y;}
}
7/5/2024 Andargie Mekonnen 23
Java Applet Methods
create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler.
The rmic tool invokes the RMI compiler and creates stub and skeleton [Link]
AdderRemote
Start the registry service by the rmiregistry tool
Now start the registry service by using the rmiregistry tool. If you don't specify the port
number, it uses a default port number. In this example, we are using the port number
5000.
rmiregistry 5000
7/5/2024 Andargie Mekonnen 24
RMI Example
Create and run the server application
Now rmi services need to be hosted in a server process.
The Naming class provides methods to get and store the remote object.
The Naming class provides 5 methods.
7/5/2024 Andargie Mekonnen 25
RMI Example
public static [Link] lookup([Link]) throws It returns the reference of the remote
[Link], [Link], object.
[Link];
public static void bind([Link], [Link]) throws It binds the remote object with the given
[Link], [Link], name.
[Link];
public static void unbind([Link]) throws It destroys the remote object which is
[Link], [Link], bound with the given name.
[Link];
public static void rebind([Link], [Link]) throws It binds the remote object to the new
[Link], [Link]; name.
public static [Link][] list([Link]) throws It returns an array of the names of the
[Link], [Link]; remote objects bound in the registry.
7/5/2024 Andargie Mekonnen 26
RMI Example
In this example, we are binding the remote object by the name sonoo.
import [Link].*;
import [Link].*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
[Link]("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){[Link](e);}
}
}
7/5/2024 Andargie Mekonnen 27
RMI Example
Create and run the client application
At the client we are getting the stub object by the lookup() method of the Naming class
and invoking the method on this object.
In this example, we are running the server and client applications, in the same machine
so we are using localhost.
If you want to access the remote object from another machine, change the localhost to
the host name (or IP address) where the remote object is located.
7/5/2024 Andargie Mekonnen 28
RMI Example
import [Link].*;
public class MyClient{
public static void main(String args[]){
try{
Adder stub=(Adder)[Link]("rmi://localhost:5000/sonoo");
[Link]([Link](34,4));
}catch(Exception e){}
}
}
7/5/2024 Andargie Mekonnen 29
7/5/2024 Andargie Mekonnen 30