0% found this document useful (0 votes)
41 views13 pages

Java Socket Programming Overview

The document discusses network programming in Java, specifically socket programming and remote method invocation (RMI). It covers key concepts like sockets, servers, clients, and how they communicate. It provides code examples for a basic Java server-client program that establishes a connection and allows sending/receiving messages. It also explains RMI concepts like remote interfaces, stubs, skeletons, and provides a step-by-step example to calculate factorials remotely using RMI.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views13 pages

Java Socket Programming Overview

The document discusses network programming in Java, specifically socket programming and remote method invocation (RMI). It covers key concepts like sockets, servers, clients, and how they communicate. It provides code examples for a basic Java server-client program that establishes a connection and allows sending/receiving messages. It also explains RMI concepts like remote interfaces, stubs, skeletons, and provides a step-by-step example to calculate factorials remotely using RMI.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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 [Link], 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 "[Link]", or a textual representation of its IP address. The
[Link] class provides methods to get the IP of any host name for example [Link],
[Link] 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 [Link] 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 “[Link]”.
Interface Program ([Link])

1. import [Link].*;
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 “[Link]”.

Advanced Programming in Java Lecture notes by: Jerusalem F 7


Implementation Program ([Link])
1. import [Link].*;
2. import [Link].*;
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 “[Link]”.
Server Program ([Link])
1. import [Link].*;
2. import [Link].*;
3. public class rser {
4. public static void main(String arg[]) {
5. try {
6. rimp ri = new rimp();
7. [Link]("rser", ri);
8. } catch (Exception e) {
9. [Link](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 “[Link]”.
Client Program ([Link])
1. import [Link].*;
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) [Link]("rmi://[Link]/rser");
6. double s = [Link](5);
7. [Link]("Factorial value is… : " + s);
8. } catch (Exception e) {
9. [Link](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 [Link].*;
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 [Link] package. Also, a default constructor needs to be created to throw the
[Link] from its parent constructor in class.
// Java program to implement the Search interface
import [Link].*;
import [Link].*;
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 ([Link]("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 [Link].*;

Advanced Programming in Java Lecture notes by: Jerusalem F 10


• import [Link].*;
• 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
• [Link](1900);
• // Binds the remote object by the name
• // ghionacademy
• [Link]("rmi://localhost:1900"+ "/ ghionacademy ",obj);
• }
• catch(Exception e) {
• [Link](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 [Link].*;
• 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)[Link]("rmi://localhost:1900"+ "/ghionacademy");
• answer = [Link](value);
• [Link]("Article on " + value + " " + answer + " at Ghion Academy ");
• }
Advanced Programming in Java Lecture notes by: Jerusalem F 11
• catch(Exception e) {
• [Link](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

Common questions

Powered by AI

A Java RMI setup requires several essential components: a remote interface, an implementation of that interface, and mechanisms for communication, specifically Stub and Skeleton objects. The remote interface declares the methods accessible to remote clients, while the implementation provides the actual method definitions. The Stub object resides on the client side and acts as a proxy, performing method invocations that are passed to the server side. The Skeleton object is on the server side and receives requests from the Stub, forwarding them to the actual server object .

Java treats socket communications similarly to I/O operations, allowing programs to read from or write to sockets as easily as they can with files. This is because Java uses streams for both types of operations. Therefore, once a connection is established using sockets, data can be sent and received much like reading from or writing to a file .

In a Java RMI implementation, methods in a remote interface must throw RemoteException, which serves as a marker that tells the compiler these methods can be invoked remotely. This exception is critical as it manages network-related issues that can occur during remote calls, such as communication failures, and informs the client about potential problems during method execution in a distributed environment .

The InetAddress class can be used to perform DNS lookups and is helpful in retrieving the IP address or hostname of a machine. The method getLocalHost() returns the InetAddress object representing the local host, while getByName() can obtain information for a remote host. If these methods fail to find the host information, they throw an UnknownHostException .

To read content from a URL in Java, the process begins by creating a URL object from a string that represents the URL address. A BufferedReader is then instantiated, using an InputStreamReader with the URL's input stream as its source. The content is read using the readLine() method of BufferedReader, enabling the program to handle input efficiently as it would from any stream .

Java RMI facilitates method invocation on objects located in different JVMs using the Stub and Skeleton objects to handle this communication. The Stub resides on the client side and acts as a local representative of the remote object. It sends the invocation request to the server. The Skeleton exists on the server side and passes the request from the Stub to the actual remote object, executing the desired method and communicating the result back to the Stub. This setup abstracts the details of network communication from the developer .

Creating and executing a Java server application using RMI involves several considerations. First, define a remote interface specifying the methods one can call remotely. Implement this interface in a class extending UnicastRemoteObject, and create a client and server application wherein the server binds the remote object to a registry using Naming.rebind(). The client uses Naming.lookup() to reference the remote object. It is vital to ensure network permissions allow registry access and provides a secure networking environment. Moreover, the rmic tool needs to generate necessary Stub and Skeleton classes for remote communication .

To establish a socket connection in Java, the server must first create a server socket bound to a specific port and remain in a listening state to accept client requests. The client attempts to connect to the server using the server's IP address and the port. Once connected, communication can occur through the sockets using streams. It is crucial that the server is running before a client attempts to connect; otherwise, the connection will be refused. The assigned port must not be blocked by firewalls or in use by other applications. Port numbers below 1024 should generally be avoided by non-privileged services .

Implementing the UnicastRemoteObject class in a Java RMI server application is critical because it enables the creation of remote object instances that can be accessed over the network. By extending UnicastRemoteObject, the server application ensures that objects are capable of handling remote method invocations. This setup also provides the necessary infrastructure for communication over TCP/IP, facilitating the remote procedure calls necessary for distributed systems .

The InetAddress class aids in discovering a machine's IP address or hostname through methods like getLocalHost() and getByName(), which return the IP address and hostname of the local or a named remote host, respectively. This capability is crucial in network application development as it facilitates the determination of network addresses required for socket connections and DNS operations, ensuring the correct host identification and communication within networked applications .

You might also like