Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Java Programming Chapter-6 Networking-1

Uploaded by

abebaw
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Java Programming Chapter-6 Networking-1

Uploaded by

abebaw
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Chapter Six

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.

 When a computer needs to communicate with another computer, it needs to know

the other computer’s address.

 An Internet Protocol (IP) address uniquely identifies the computer on the


Internet.

 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…

 Two protocols used in conjunction with the IP are the Transmission


Control Protocol (TCP) and the User Datagram Protocol (UDP).

 TCP enables two hosts to establish a connection and exchange


streams of data.

 TCP guarantees delivery of data and also guarantees that packets


will be delivered in the same order in which they were sent.

 UDP is connectionless, host-to-host protocol that is used over the IP.

4
Introduction…
 Java supports both stream-based and packet-based
communications.

 Stream-based communications use TCP for data transmission.

 Packet-based communications use UDP for data transmission.

 Since TCP can detect lost transmissions and resubmit


them,

 transmissions are lossless and reliable.

 UDP cannot guarantee lossless transmission.

5
Client/Server Computing
 Networking is tightly integrated in Java.

 Java API provides the classes for creating sockets to


facilitate program communications over the Internet.

 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.

6
Client/Server Computing…
 Network programming usually involves a server and one or
more clients.

 The client sends requests to the server, and the


server responds.

 The server can accept or deny the connection.

 The client begins by attempting to establish a


connection to the server.

 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. 7
The Server Socket
 To establish a server,
 you need to create a server socket and attach it to a port –
 the point at which the server listens for connections.

 Port is a software address of a computer on the network.

 The port identifies the TCP service on the socket.

 To communicate program over the network first Create a


socket and attach it to the port.

 Port numbers range from 0 to 65536,

 port numbers 0 to 1024 are reserved for privileged services.

 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.

 The following statement creates a server socket


serverSocket:
 ServerSocket serverSocket = new ServerSocket(port);

 After a server socket is created, the server can use the


following statement to listen for connections:
 Socket socket = serverSocket.accept();
 This statement waits until a client connects to the server
socket.
9
The Client Socket
 The client issues the following statement to
request a connection to a server:
 Socket socket = new Socket(serverName, port);

 ServerName is the server’s host name or IP address.

 The following statement creates a socket at port 8000 on


the client machine to connect to the host130.254.204.36:
 Socket socket = new Socket("130.254.204.36", 8000);
 Socket socket = new Socket("Domain Name", 8000);

10
The Client Socket…

The server creates a server socket and, once a


connection to a client is established, connects to the
client with a client socket.
11
Data Transmission Through Sockets
 Communication between server and client is conducted the same as I/O streams.

 To get an input stream and an output stream, use the getInputStream() and
getOutputStream() methods on a socket object.

E.g. InputStream input = socket.getInputStream();

OutputStream output = socket.getOutputStream();

 The InputStream and OutputStream streams are used to read or write bytes.

 You can use DataInputStream, DataOutputStream, BufferedReader, and


PrintWriter to wrap on the InputStream and OutputStream to read or write data,
such as int, double, or String.
 DataInputStream input = new DataInputStream(socket.getInputStream());

 DataOutputStream output = new DataOutputStream(socket.getOutputStream());

 The server can use input.readDouble() to receive a double value from the client;

output.writeDouble(d) to send double value d to 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…

 Example: The client sends the radius to the server; the


server computes the area and sends it to the client.

(a) The client sends the radius to the


server.
(b) The server sends the area to the client
14
Example: Server
import java.io.*; import java.net.*;
import java.util.*; import java.awt.*;
import javax.swing.*;
public class Server extends JFrame {
private JTextArea jta = new JTextArea();
public static void main(String[] args) {
Server obj=new Server();
}
public Server() {
setLayout(new BorderLayout());
add(jta, BorderLayout.CENTER);
setTitle("Server");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true);

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());

 InetAddress has three static methods :-

 public static InetAddress getByName(String hostName)

 public static InetAddress[] getAllByName(String hostName)

 public static InetAddress getLocalHost( )

22
The InetAddress Class…
 Example - A program that prints the address of host

import java.net.*;

public class HostName {


public static void main (String[] args) { try {
InetAddress address=InetAddress.getByName("www.google.com");
System.out.println(address);
}
catch (UnknownHostException ex) { System.out.println("Could
not find www.google.com");
}
}
23
}
The InetAddress Class…
 Some computers have more than one Internet address.
 Given a hostname, InetAddress.getAllByName() returns an
array that contains all the addresses corresponding to that
name.
 Example
import java.net.*;
public class AllAddressOfGoogle {
public static void main (String[] args) { try {
InetAddress[] addresses = InetAddress.getAllByName("www.google.com"); for (int
i = 0; i < addresses.length; i++) {
System.out.println(addresses[i]);
}
}
catch (UnknownHostException ex) {
System.out.println("Could not find www.google.com");
}
}
}

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

Note: Start the server first, then start 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);

jta.append("MultiThreadServer started at " + new Date() + '\n');


int clientNo = 1;
while (true) {
// Listen for a new connection request
Socket socket = serverSocket.accept();
jta.append("Starting thread for client " + clientNo + " at " + new
Date() + '\n');
InetAddress inetAddress = socket.getInetAddress();
jta.append("Client " + clientNo + "'s host name is "+ inetAddress.getHostName()+ "\n");
jta.append("Client " + clientNo + "'s IP Address is " + inetAddress.getHostAddress()+ "\n");
// Create a new thread for the connection

HandleAClient task = new HandleAClient(socket);


new Thread(task).start();
clientNo++;
}
}
catch(IOException ex) {
System.err.println(ex);
}} 29
Example…
class HandleAClient implements Runnable {
private Socket socket;

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 .

 This definition h a s two aspects:


 hardware: autonomous machines
 software: a single s y s t e m view for the u s e r s

33
Characteristics of Distributed Systems
 between the computers and the ways
theycommunicate are hidden from users

 users and applications can interact with a distributed


system in a consistent and uniform way regardless of
location (Reliability)

 distributed systems should be easy to expand and


grows with demand (Scalability)

 a distributed system is normally continuously available,


even if there may be partial failures (Availability)
34
R e m o t e M e t h o d I n v o c a t i o n ( R MI)
 RMI is a distributed object system that enables you to
easily develop distributed J a v a applications.
 Extension of local method invocation that allows an object living in one
process to invoke the methods of an object living in another process

 An RMI application is often composed of two separate programs,


a server and a client.
 The object whose method makes the remote call is called the
client object.
 The remote object is called the server object.

 The computer running the J a v a code that calls the remote


method is the client for that call, a n d the computer hosting the
35
Stubs and Parameter Marshaling
 When client code wants to invoke a remote method on a remote object,
it actually calls a client stub.

 The stub resides on the client machine, not on the server.

 A stub acts a s a client local representative for the remote object.

 The client invokes a method on the local stub.

 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.

The process of encoding the parameters is called parameter marshalling


 Purpose: to convert the parameters into a format suitable for transport
from one virtual machine to another.

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;

 A description of the method to be called;

 Then the client stub performs the following actions

 Ma rsh a ls pa ram eters in device independen t format.


 Sends th is information to th e s erver(i. e remote object
ID, method, and parameters)
 Waits for reply.

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:

 It unmarshals the parameters.

 It locates the object to be called.

 It calls the desired method.

 It captures and marshals the return value

 It s ends a pa ckage con sistin g of th e m a rsh a lled


return data back to the stub on the client.
38
Stubs…

Common organization of a remote object with client-side stub

39
RMI Registry
• Is a simple name server provided for storing references to
remote objects.

• The server is responsible for registering remote objects with


the registry service.

 The registry keeps track of the addresses of remote objects.

 A remote object can be stored on RMI registry using the


methods defined in java.rmi.Naming class.

 A client can obtain a reference to a remote object by


looking up in the RMI registry.
40
RMI
Registry…

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

to the registry bind


RMI Server
• The client lookup the server name in
the registry to establish remote Registry
skeleton
references.
• The Stub serializing the parameters
lookup
to skeleton, the skeleton invoking return call

the remote method and serializing


the result back to the stub. stub

RMI Client

Local Machine
Creating RMI Applications

steps

 Define a remote interface

 Implementing the interface

 Writing the server class

 Writing RMI client

 Compile the Java source files

 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

 must extend the interface java.rmi.Remote

 every method in the interface must declare that it

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.

 This allows the method to be called remotely.

 It must be declared public, in order for clients to be able to


load remote objects which implement the remote interface

 All remote methods are required to be declared to throw


RemoteException.

 This forces the programmer to handle unexpected failure


of the network or remote machine
47
Implementing the interface
 The next step is to define a class that implements this remote interface.
 This class extends the library class
 java.rmi.server.UnicastRemoteObject.
 UnicastRemoteObject provides a number of methods that make remote
method invocation work.
 In particular, it marshals and unmarshals remote references to the object.
 We have to declare a default constructor, even when we don't have any
initialization code for our service.
 This is because our default constructor can throw a
java.rmi.RemoteException from its parent constructor in
UnicastRemoteObject.
 The server uses the RMISecurityManager to protect its resources while 48
Implementing the interface

Here is the source code of the interface implementation (sumimpl.java)


public class Sumimpl extends UnicastRemoteObject implements sum {
public sumimpl() throws RemoteException {
super();
}
// Implemplement the remote methods
public int sum(int x, int y) throws RemoteException
{
return(x+y); }
}
Writing th e server class
we need to write a server that makes the remote object available to the
world.

 Ou r server class needs to have a main method.

 The main method will be responsible for creating a n instance of


sumimpl and registering (or binding) the object to the name on
the RMI Registry.

 The RMI registry is a naming service: it keeps track of the available


objects and the names by which they can be requested.

 Name arguments takes the following URL form: (rmi://host:port/name)


Use java.rmi.Naming class:
• Server must bind its name to the registry.
• Client used to lookup the server name. 50
Writing the server class…
import java.rmi.*;
public class sumserver {
public static void main(String args[ ]) {
try {
System.out.println("Constructing server implementations...");
//create a local instance of the object

sumimpl sumobj= new sumimpl();

System.out.println("Binding remote object implementations to registry...");

Naming.rebind(“rmi://localhost/sum", sumobj);

System.out.println("Waiting for invocations from clients...");

} catch(Exception e) { System.out.println("Error:" + e);


}
}

} 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.

 A program retrieves this remote reference from a registry on


the server where the remote object runs.

 The call to Naming.lookup() searches in a remote RMI


registry.

 This example assumes the remote object lives on the host


“localhost”, and has been registered in the default RMI
registry (on port 1099) on that machine.
52
Writing R MI client …
import java.rmi.* ;
public class sumclient {
public static void main(String [] args){
try{ / / g e t t h e re m o te o b j e c t f ro m t h e re g i s t r y
sum sumobj=(sum) Naming.lookup("rmi://localhost/sum");
int result=sumobj.sum(13,14);
System.out.println("the sum is:"+result);
}
catch(Exception e)
{
e.printStackTrace();
}
}}
53
Running the client and server
 Step 1, compile all of your code
 J a v a c *.java

 Step 2, create stub file


 rmic sumImpl

 Step 3, start the RMI regestry


 start rmiregistry

 Step 4, start the server


 start java sumServer

 Step 5, start the client


 J a v a sumClient
54

You might also like