Java Programming Chapter-6 Networking-1
Java Programming Chapter-6 Networking-1
Networking in Java
Objectives
In this chapter you will learn:
To implement Java networking using
applications by
sockets.
To understand how to implement Java clients
and
servers
To that communicate
obtain with one another.
Internet addresses the InetAddress
using class
To construct a multithreaded server.
2
Introduction
Computer network – is the interconnection of computer and different digital
devices in order to share resource, exchange files and allow electronic
communication.
An IP address consists of four dotted decimal numbers between 0 and 255, such as
130.254.204.36.
Since it is not easy to remember so many numbers, they are often mapped to
meaningful names called domain names, such as www.Google.com.
3
Introduction…
4
Introduction…
Java supports both stream-based and packet-based
communications.
5
Client/Server Computing
Networking is tightly integrated in Java.
6
Client/Server Computing…
Network programming usually involves a server and one or
more clients.
For instance, the email server runs on port 25, and the
Web server usually runs on port 80. Telnet 23, FTP 21 8
The Server Socket…
You can choose any port number that is not
currently used by any other process.
10
The Client Socket…
To get an input stream and an output stream, use the getInputStream() and
getOutputStream() methods on a socket object.
The InputStream and OutputStream streams are used to read or write bytes.
The server can use input.readDouble() to receive a double value from the client;
12
Data Transmission Through Sockets…
The server and client exchange data through I/O streams on top of
the socket.
13
Data Transmission Through Sockets…
15
Example: Server…
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("Server started at " + new Date() + '\n');
// Listen for a connection request
Socket socket = serverSocket.accept();
// Create data input and output streams
DataInputStream inputFromClient = new DataInputStream(socket.getInputStream());
DataOutputStream outputToClient = new DataOutputStream(socket.getOutputStream());
while (true) {
// Receive radius from the client
double radius = inputFromClient.readDouble();
double area = radius * radius * Math.PI;
// Send area back to the client
outputToClient.writeDouble(area);
jta.append("Radius received from
client: " + radius + '\n');
jta.append("Area found: " + area + '\
n');
}
}
catch(IOException ex)
{ System.err.println(ex);
}}}
16
Example: Client
import java.io.*; import
java.net.*; import java.awt.*;
import java.awt.event.*; import
javax.swing.*;
public class Client extends JFrame {
// Text field for receiving radius
private JTextField jtf = new
JTextField();
// Text area to display contents
private JTextArea jta = new JTextArea(); // IO streams
private DataOutputStream toServer;
private DataInputStream fromServer;
public static void main(String[] args) {
Client obj = new Client();
}
17
Example: Client…
public Client() {
// Panel p to hold the label and text field
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new JLabel("Enter radius"), BorderLayout.WEST);
p.add(jtf, BorderLayout.CENTER);
jtf.setHorizontalAlignment(JTextField.LEFT);
setLayout(new BorderLayout());
add(p, BorderLayout.NORTH);
add(jta, BorderLayout.CENTER);
jtf.addActionListener(new TextFieldListener());
setTitle("Client");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);
18
Example: Client…
try {
// Create a socket to connect to the server
Socket socket = new Socket("130.254.204.36", 8000);
// Create an input stream to receive data from the server
fromServer = new
DataInputStream( socket.getInputStream());
// Create an output stream to send data to the server
toServer = new
DataOutputStream(socket.getOutputStream());
}
catch (IOException ex)
{ jta.append(ex.toString() + '\
n');
}
}
19
Example: Client…
private class TextFieldListener implements ActionListener
{ public void actionPerformed(ActionEvent e) {
try {
// Get the radius from the text field
double radius = Double.parseDouble(jtf.getText().trim());
// Send the radius to the
server
toServer.writeDouble(radius);
toServer.flush();
double area = fromServer.readDouble() ;
jta.append("Radius is " + radius + "\
n");
jta.append("Area received from the
server is “ + area + '\n');
}
catch (IOException ex) {
System.err.println(ex);
}
}
} 20
Output
21
The InetAddress Class
To find the client’s host name and IP address.
You can use an instance of InetAddress on a socket that
connects to the client.
InetAddress inetAddress = socket.getInetAddress();
Then, you can display the client’s host name and IP address, as
follows:
System.out.println("Client's host name is " + inetAddress.getHostName());
System.out.println("Client's IP Address is " + inetAddress.getHostAddress());
22
The InetAddress Class…
Example - A program that prints the address of host
import java.net.*;
24
The InetAddress Class…
InetAddress.getLocalHost() returns the
InetAddress of the machine on which it's
running.
Example
import java.net.*;
public class MyAddress {
public static void main (String[] args) { try {
InetAddress address =
InetAddress.getLocalHost( );
System.out.println(address);
}
catch (UnknownHostException ex) { System.out.println("Could not find
this computer's address.");
}
}
}
25
Serving Multiple Clients
A server can serve multiple clients.
The connection to each client is handled by one thread.
Multiple clients are quite often connected to a single server at the same time.
You can use threads to handle the server's multiple clients simultaneously.
Simply create a thread for each connection.
Here is how the server handles the establishment of a connection:
while (true) {
Socket socket = serverSocket.accept();
Thread thread = new ThreadClass(socket);
thread.start();
}
The server socket can have many connections.
Each iteration of the while loop creates a new connection.
Whenever a connection is established, a new thread is created to handle
communication between the server and the new client; and this allows multiple
connections to run at the same time.
26
Example: Serving Multiple Clients
27
Example
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
public class MultiThreadServer extends JFrame {
private JTextArea jta = new JTextArea();
public static void main(String[] args) {
new MultiThreadServer();
}
public MultiThreadServer()
{ setLayout(new
BorderLayout());
add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("MultiThreadServer");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
28
Example…
try {
ServerSocket serverSocket = new ServerSocket(8000);
public HandleAClient(Socket
soc) { socket = soc;
}
public void
run() { try {
DataInputSt
ream
inputFromC
lient = new
DataInputSt
ream(socket.
getInputStre
am());
DataOutputStream outputToClient = new
DataOutputStream(socket.getOutputStream()); while (true) {
double radius =
inputFromClient.readDouble(); double
area = radius * radius * Math.PI;
outputToClient.writeDouble(area);
jta.append("radius received from client: " + radius +
'\n'); jta.append("Area found: " + area + '\n');
}}
catch(IOException
30
Remote Method Invocation (RMI)
31
Objective:
Understand the role of distributed objects in
application development.
Write J a v a programs that communicate through
distributed object with remote objects.
32
Definition:
A d i s t r i b u t e d s y s t e m is a collection of independent computers
that appears to its us er s a s a single coherent s y s t e m .
33
Characteristics of Distributed Systems
between the computers and the ways
theycommunicate are hidden from users
The stub packages the parameters used in the remote method into a
block of bytes. This packaging uses a device-independent encoding for
each parameter.
36
Stubs…
Th e s tu b meth od on th e client bu ilds a n information block
that consists of:
An identifier of the remote object to be used;
37
Stubs…
The server s t u b ( Skeleton),
Skeleton object resides on server program.
It is responsible for passing request from Stub to remote
object.
It perform the following actions for every remote method call:
39
RMI Registry
• Is a simple name server provided for storing references to
remote objects.
41
Entities involved in RMI Application
1. A remote object is an object on another computer
2. The server object is the object receiving the request
3. Client: program written to access remote methods
4. Server: program written to implement the remote methods
Clients connect to the server and request that a method be executed.
5. Object registry: is a program
• runs on a known port (1099 by default)
• A server, upon starting, registers its objects with a textual name in
the object registry.
• A client, before invoking a remote method, must first contact the
object registry to obtain access to the remote object.
General RMI Architecture
• The server must first bind its name Remote Machine
RMI Client
Local Machine
Creating RMI Applications
steps
Start registry
Start server
Define a remote interface
To create an RMI application, the first step is the defining of a
remote interface between the client and server objects.
The interface definition:
must be public
thows java.rmi.RemoteException
but other exceptions may be thrown as well
Eg. a simple program that accepts two numbers from the client and
returns their sum.
An interface is a description of the methods we will allow remote
clients to invoke.
In our example, we need a method that accepts as a
parameter two integers, adds them, and returns their s u m
45
Define a remote interface…
public int s u m ( int x, int y);
Once we've decided on the method that will compose our
service, we have to create a J ava interface.
An interface is a class which contains abstract methods;
these methods must be implemented by another class.
Here's the source code for our service that calculates the
s u m of two integers.(sum.java)
import java.rmi.RemoteException;
public interface S u m extends java.rmi.Remote
{
/ / Calculate the s u m of two numbers
public int s u m ( int x , int y )throws RemoteException;
}
46
Define a remote interface…
O u r interface extends java.rmi.Remote, which indicates that
this is a remote service.
Naming.rebind(“rmi://localhost/sum", sumobj);
} 51
Writing RMI client
Before a client object can call a remote method, it needs a
remote reference to the object whose method it's going to
call.