Network Computing

download Network Computing

of 19

Transcript of Network Computing

  • 7/28/2019 Network Computing

    1/19

    NETWORK COMPUTING (RT605)

    Module 4

    NETWORK PROGRAMMING

    Introduction

    A computer network, often simply referred to as a network, is a group of computers and

    devices interconnected by communications channels that facilitate communications among users and

    allows users to share resources. A computer network allows sharing of hardware and software

    resources and information among interconnected devices.

    A network topology represents its layout or structure from the point of view of data flow. It

    defines the way in which computers, printers, and other devices are connected, physically and

    logically. A network topology describes the layout of the wire and devices as well as the paths used

    by data transmissions. Common types of network topologies include bus, star, ring and mesh.

    LAN

    A local area network (LAN) is a network that connects computers and devices in a limited

    geographical area such as home, school, computer laboratory, office building, or closely positioned

    group of buildings. Each computer or device on the network is a node. Current wired LANs are most

    likely to be based on Ethernet technology. The purpose of interconnection would be to share files,

    share programs and decentralize specialized functions. Another reason for creating a local area

    network is also to share the use of expensive peripherals such as fast printers, large disks, graphics

    workstations, etc.

    WAN

    Wide Area Network (WAN) is a telecommunication network that covers a broad area (i.e.,any network that links across metropolitan, regional, or national boundaries). Business and

    government entities utilize WANs to relay data among employees, clients, buyers, and suppliers from

    various geographical locations. Computers connected to a wide-area network are often connected

    through public networks, such as the telephone system. They can also be connected through leased

    lines or satellites.

    MAN

    A metropolitan area network (MAN) is a computer network that usually spans a city or a

    large campus. A MAN usually interconnects a number of local area networks(LANs) using a high-

    capacity backbone technology, such as fiber-optical links, and provides up-link services to wide area

    networks(or WAN) and the Internet.

    VPN

    A virtual private network (VPN) is a network that uses primarily public telecommunication

    infrastructure, such as the Internet, to provide remote offices or traveling users an access to a central

    organizational network.

    Wireless LANs

    A wireless local area network (WLAN) links two or more devices using some wireless

    distribution method (typicallyspread-spectrumorOFDMradio), and usually providing a connection

    through an access point to the wider internet. For example, Wi-Fi.

    Module 4 1

    http://www.webopedia.com/TERM/L/leased_line.htmlhttp://www.webopedia.com/TERM/L/leased_line.htmlhttp://en.wikipedia.org/wiki/Computer_networkhttp://en.wikipedia.org/wiki/Computer_networkhttp://en.wikipedia.org/wiki/Local_area_networkhttp://en.wikipedia.org/wiki/Local_area_networkhttp://en.wikipedia.org/wiki/Wide_area_networkhttp://en.wikipedia.org/wiki/Wide_area_networkhttp://en.wikipedia.org/wiki/Wide_area_networkhttp://en.wikipedia.org/wiki/Internethttp://en.wikipedia.org/wiki/Internethttp://en.wikipedia.org/wiki/Spread_spectrumhttp://en.wikipedia.org/wiki/Spread_spectrumhttp://en.wikipedia.org/wiki/Spread_spectrumhttp://en.wikipedia.org/wiki/OFDMhttp://en.wikipedia.org/wiki/OFDMhttp://en.wikipedia.org/wiki/OFDMhttp://www.webopedia.com/TERM/L/leased_line.htmlhttp://www.webopedia.com/TERM/L/leased_line.htmlhttp://en.wikipedia.org/wiki/Computer_networkhttp://en.wikipedia.org/wiki/Local_area_networkhttp://en.wikipedia.org/wiki/Wide_area_networkhttp://en.wikipedia.org/wiki/Wide_area_networkhttp://en.wikipedia.org/wiki/Internethttp://en.wikipedia.org/wiki/Spread_spectrumhttp://en.wikipedia.org/wiki/OFDM
  • 7/28/2019 Network Computing

    2/19

    Protocols

    HTTP: Hyper Text Transfer Protocol is the protocol that web browsers and servers use to transfer

    hypertext pages and images. It is quite a simple protocol for a basic page-browsing web server. When

    a client requests a file from an HTTP server, an action known as a hit, it simply prints the name of the

    file in a special format to a predefined port and reads back the contents of the file. The server also

    responds with a status code number to tell the client whether the request can be fulfilled and why.

    TCP: Transmission Control Protocol provides a reliable, connection-oriented, continuous-stream

    protocol that client-server applications on the Internet use to communicate with each other. TCP sets

    up a connection with a remote system by transmitting control information, often known as a

    handshake, before beginning a communication. To communicate over TCP, a client program and a

    server program establish a connection to one another. Each program binds a socket to its end of the

    connection. To communicate, the client and the server each reads from and writes to the socket bound

    to the connection.

    TCP uses a three-way handshaking procedure to set-up a connection. A connection is set up by the

    initiating side sending a segment with the SYN flag set and the proposed initial sequence number in

    the sequence number field (seq = X). The receiver then returns a segment with both the SYN andACK flags set with the sequence number field set to its own assigned value for the reverse direction

    (seq = Y) and and acknowledge field of X + 1 (ack = X + 1). On receipt of this, the initiating side

    makes a note of Y and returns a segment with just the ACK flag set and an acknowledgement field of

    Y + 1.

    IP: Internet Protocol is the keystone of the TCP/IP suite. The data on the Internet flows through IP

    packets. IP is termed a connectionless, unreliable protocol. As a connectionless protocol, IP does not

    exchange control information before transmitting data to a remote system packets are merely sent to

    the destination with the expectation that they will be treated properly. IP is unreliable because it does

    not retransmit lost packets or detect corrupted data. An IP address is a 32-bit number, and eachstandard address is unique on the Internet. Given an IP packet, the information can be routed to the

    destination based upon the IP address defined in the packet header.

    UDP: User Datagram Protocol is a connection less, unreliable protocol. UDP is a low-overhead

    alternative to TCP for host-to-host communications. Message-oriented UDP enables applications to

    send self-contained messages within UDP datagrams, the unit of UDP transmission. UDP provides

    the addressing scheme of ports, allowing for many applications to simultaneously send and receive

    datagrams. UDP has no mechanism for detecting errors, nor retransmitting lost or corrupted

    information. UDP does not negotiate a connection before transmitting data. Information is sent with

    the assumption that the recipient will be listening.

    FTP: File Transfer Protocol is a standard network protocol used to copy a file from one host toanother over a TCP/IP-based network, such as the Internet. FTP is built on client-server architecture

    Module 4 2

  • 7/28/2019 Network Computing

    3/19

    and utilizes separate control and data connections between the client and server. FTP is most

    commonly used to download a file from a server using the Internet or to upload a file to a server such

    as uploading a Web page to a server.

    Client / Server

    Network programming involves 2 types of programs: Client programs and Server programs.

    Client: The client knows the hostname of the machine on which the server is running and the port

    number on which the server is listening. The client requests for a connection with the server on the

    server's machine and port. The client also needs to identify itself to the server so it binds to a local

    port number that it will use during this connection.

    Server: A server runs on a specific computer and has a socket that is bound to a specific port number.

    The server just waits, listening to the socket for a client to make a connection request. There are

    compute servers, which provide computing power; print servers, which manage a collection of

    printers; disk servers, which provide networked disk space; and web servers, which store web pages.

    Proxy Servers

    A proxy server speaks the client side of a protocol to another server. This is used when clients

    have certain restrictions on which servers they can connect to. Thus, a client would connect to a proxy

    server, which did not have such restrictions, and the proxy server would in turn communicate for the

    client. A proxy server has the additional ability to filter certain requests or cache the results of those

    requests and reduce the bandwidth demands on a local networks connection to the Internet.

    Domain Name Service (DNS)

    The name of an internet address is called its domain name.

    Internet Addressing

    An internet address is a number that uniquely identifies each computer on the Net. Internet

    address consist of 32 bit values which was specified by IPv4 and new addressing scheme called IPv6

    uses 128 bit value.

    Java Networking Features

    Java supports TCP/IP both by extending the already established stream I/O interface and by

    adding the features required to build I/O objects across the network. Java supports both the TCP and

    UDP protocol. Thejava.net package provides many Networking Classes and Interfaces to implement

    network programming.

    Classes of java.net package

    Class Description

    ServerSocket This class implements server sockets.

    Socket This class implements client sockets.

    SocketAddress This class represents a socket address with no protocol attachment.

    InetAddressThis class represents an Internet Protocol (IP) address. It encapsulates both

    the numerical IP address and the domain name for that address.

    InetSocketAddress This class implements an IP socket address (IP address and Port number).

    Module 4 3

  • 7/28/2019 Network Computing

    4/19

    URI This class represents a Uniform Resource Identifier (URI) reference.

    URL This class represents a Uniform Resource Locator (URL) reference.

    URLConnection

    This abstract class is the super class of all classes that represent a

    communication link between the application and the URL. It can be used

    to inspect the properties of the remote object before actually transporting it

    locally.

    URLEncoder Utility class for HTML form encoding.

    URLDecoder Utility class for HTML form decoding.

    Proxy This class represents a proxy setting, typically a type and a socket address.

    DatagramPacket This class represents a datagram packet.

    DatagramSocket This class represents a socket for sending and receiving datagram packets.

    MulticastSocket This class is used for sending and receiving IP multicast packets.

    ContentHandlerThis abstract class is the super class of all classes that read an object from

    a URLConnection.

    Interfaces of java.net package

    Interface Description

    ContentHandlerFactory This interface defines a factory for content handlers.

    DatagramSocketImplFactory This interface defines a factory for datagram socket

    implementations.

    FileNameMap This interface provides a mechanism to map between a file name

    and a MIME type string.

    SocketImplFactory This interface defines a factory for socket implementations.

    SocketOptions This interface defines methods to get / set socket options.

    URLStreamHandlerFactory This interface defines a factory for URL stream protocolhandlers.

    Socket

    A socket is one end-point of a two-way communication link between two programs running

    on the network. Socket classes are used to represent the connection between a client program and a

    server program. Sockets are a programming abstraction that isolates our code from the low-level

    implementations of the TCP/IP protocol stack. The java.net package provides two classes--Socket and

    ServerSocket--that implement the client side of the connection and the server side of the connection,

    Module 4 4

  • 7/28/2019 Network Computing

    5/19

    respectively. A socket is bound to a port number so that the TCP layer can identify the application that

    data is destined to be sent.

    Connection oriented sockets are based on TCP

    Connectionless sockets are based on UDP

    Reserved Sockets and Ports

    Ports can be considered as numbered sockets on a particular machine. Port numbers range

    from 0 to 65,535. The port numbers ranging from 0 to 1023 are restricted or reserved for the use of

    well known services such as HTTP and FTP and other system services. These ports are called well

    known ports. TCP/IP reserves the lower 1,024 ports for specific protocols.

    21 is for FTP

    23 is for Telnet

    25 is for e-mail or SMTP

    80 is for HTTP

    TCP / IP Socket

    A socket is a handle to a communications link over the network with another application. A

    TCP socket uses the TCP protocol, inheriting the behaviour of that transport protocol. Sockets are

    often used in client/server applications. A centralized service waits for various remote machines to

    request specific resources, handling each request as it arrives.

    Four pieces of information are needed to create a TCP socket:

    The local system's IP address

    The TCP port number the local application is using

    The remote system's IP address

    The TCP port number to which the remote application is responding

    Connection:

    The server listens for client requests and accepts the connection. Upon acceptance, the server

    gets a new socket bound to the same local port and also has its remote endpoint set to the address and

    port of the client. It needs a new socket so that it can continue to listen to the original socket for

    connection requests while tending to the needs of the connected client.

    Module 4 5

  • 7/28/2019 Network Computing

    6/19

    On the client side, if the connection is accepted, a socket is successfully created and the client

    can use the socket to communicate with the server. The client and server can now communicate by

    writing to or reading from their sockets.

    An endpoint is a combination of an IP address and a port number. Every TCP connection can

    be uniquely identified by its two endpoints. The java.net package in the Java platform provides a

    class, Socket, that implements one side of a two-way connection between our Java program andanother program on the network. Additionally, java.net includes the ServerSocket class, whichimplements a socket that servers can use to listen for and accept connections to clients.

    There are two kinds of TCP sockets in Java: Client ( Socket ) and Server ( ServerSocket )

    TCP/IP Client Sockets

    TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to- point,

    stream-based connections between hosts on the Internet. A socket can be used to connect Javas I/O

    system to other programs that may reside either on the local machine or on any other machine on the

    Internet. The Socket class included the java.net package implements the client socket. The Socket

    class is designed to connect to server sockets and initiate protocol exchanges. The creation of a Socketobject implicitly establishes a connection between the client and server.

    Constructors of the Socket Class

    Socket( ) : Creates an unconnected socket with system default type.

    Socket(String hostName, int port) : Creates a socket connecting the local host to the named host and

    the specified port. It may throw an UnknownHostException or an IOException.

    Socket(InetAddress ipAddress, int port) : Creates a socket using a preexisting InetAddress object

    and the specified port. It may throw an IOException.

    Methods of the Socket Class

    int getPort( ) : Returns the remote port to which this Socket object is connected.

    int getLocalPort( ) : Returns the local port to which this Socket object is connected.

    void bind(SocketAddress bindpoint) : Binds the socket to a local address.

    void connect(SocketAddress endpoint) : Connects this socket to the server.

    void close( ) : Closes the socket.

    TCP/IP Server Sockets

    Java has a ServerSocket class (included in java.net) that must be used for creating server

    applications. The ServerSocket class is designed to be a listener, which waits for clients to connect

    before doing anything. It is used to create servers that listen for either local or remote client programs

    to connect to them on published ports. ServerSocket will register itself with the system as having an

    interest in client connections. The constructors for ServerSocket reflect the port number that we wish

    to accept connections on. The queue length tells the system how many client connections it can leave

    pending before it should simply refuse connections. The default is 50. ServerSocket has a method

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

    Constructors of the ServerSocket Class

    ServerSocket( ) : Creates an unbound server socket.

    Module 4 6

  • 7/28/2019 Network Computing

    7/19

    ServerSocket(int port) : Creates a server socket bound to the specified port. The queue length is 50.

    ServerSocket(int port, int maxQueue, InetAddress localAddress) : Creates a server socket on the

    specified port with a maximum queue length of maxQueue. On a multihomed host, localAddress

    specifies the IP address to which this socket binds.

    Methods of the ServerSocket Class

    int getLocalPort( ) : Returns the local port on which this Socket object is listening.

    void bind(SocketAddress endpoint) : Binds the server socket to a specific address (IP and Port).

    void close( ) : Closes the socket.

    Socketaccept( ) : Listens for a connection to be made to this socket and accepts it.

    TCP / IP Programming with Java

    We can create Java programs to communicate between systems connected to a network. The

    client server model is commonly used to implement network programming. The client side program

    performs the functions of the client machine and the server side program handles the server machine.

    Thejava.net and java.io packages are used to implement the communication process.

    Client Side

    1. The new socket is created by using a socket() constructor

    2. The socket attempts to connect to remote host

    3. Once the connection is established the local and remote hosts get input and output streams

    from the socket

    4. Close the connection

    Server Side

    1. A new ServerSocket is created on a particular port

    2. Listens for incoming connection attempts on that port

    3. Use accept()

    4. Block other operations until a client make a network connection

    5. Return a socket object

    6. Get inputstream and outputstream

    7. Server and client interacts

    8. Server returns to step2.

    Eg:Simple Client Server Program

    The following example demonstrates a simple client - server communication in a network.

    The client receives a data input and passes it to the server, where it is displayed.

    Client.java

    Module 4 7

  • 7/28/2019 Network Computing

    8/19

    import java.io.*;

    import java.net.*;

    // Client Program

    class Client {

    Client( )

    {

    PrintWriter pw ;

    BufferedReader br ;

    String str ;

    try

    {

    Socket s = new Socket( localhost, 8000 ) ;

    br = new BufferedReader( new InputStreamReader (System.in) ) ;

    pw = new PrintWriter( s.getOutputStream( ), true ) ;

    do

    {

    str = br.readLine( ) ;

    pw.println(str) ;

    } while( !str.equals("END") ) ;

    }

    catch(Exception ex)

    {

    System.out.println(ex) ;

    }

    }

    public static void main( String args[ ] )

    {

    new Client( ) ;

    }

    }

    Module 4 8

  • 7/28/2019 Network Computing

    9/19

    The socket object s is created to establish a connection with the server named localhost at

    port number 8000. The name localhost is used when the server resides in the local machine.

    We have to use the IP address instead of localhost when the server is a remote machine.

    System.in is used to read the input fed from the clients keyboard. This input stream is

    converted into an object of the BufferedReader class, using the InputStreamReader class.

    An object of the PrintWriter class is used to send the output to the server by writing it to the

    socket.

    The readLine( ) method is used to read through the contents of the BufferedReader object.

    The try catch block is used to catch any exceptions or errors that may arise during the

    execution process.

    Server.java

    import java.io.*;

    import java.net.*;

    // Server Program

    class Server

    {

    Server( )

    {

    BufferedReader br ;

    String str ;

    try

    {

    ServerSocket ss = new ServerSocket( 8000 ) ;

    Socket s1 = ss.accept( ) ;

    br = new BufferedReader(new InputStreamReader ( s1.getInputStream( ) ) ) ;

    do

    {

    str = br.readLine( ) ;

    System.out.println(str) ;

    } while( !str.equals("END") ) ;

    }

    catch(Exception ex)

    Module 4 9

  • 7/28/2019 Network Computing

    10/19

    {

    System.out.println(ex) ;

    }

    }

    public static void main( String args[ ] )

    {

    new Server( ) ;

    }

    }

    The server socket object is created to listen to a port (8000) and accept client connections.

    The socket object s1 is created to establish a connection with the client after the server

    accepts the request for the connection.

    The input stream is received through the socket connection from the client. It is then

    converted into an object of the BufferedReader class, using the InputStreamReader class.

    The readLine( ) method is used to read through the contents of the BufferedReader object.

    System.out.println is used to print the received input on to the display screen of the server.

    The try catch block is used to catch any exceptions or errors that may arise during the

    execution process.

    Output:

    Client

    Module 4 10

  • 7/28/2019 Network Computing

    11/19

    Server

    Iterative Servers

    The iterative server handles a request and then returns the results to the client. Any new client

    requests must wait for the previous request to complete. In this model, the server application holds the

    socket until all application processing is completed. This means that after a client makes a connection

    to a server, another client cannot access the listener or the server until the first client is finished. If the

    transaction takes more time, queues can build up quickly. This type of server is sequential.

    Iterative servers are fairly simple and are suitable for transactions that do not last long. These

    can be easily programmed and used to process small, fixed size requests.

    Concurrent Servers

    A concurrent server does not handle the request itself. A separate thread or sub-process

    handles request and returns any results to the client. The server is then free to immediately service the

    Module 4 11

  • 7/28/2019 Network Computing

    12/19

    next client. The service requests are processed in parallel Hence, the client does not have to wait. This

    allows a higher degree of transaction concurrency because the listening socket is not held by a single

    client and can instead listen concurrently to multiple clients. It relies on the operating system for

    concurrency. It can use the multitasking nature of the operating system.

    Advantages:

    1. Easy to implement.

    2. Rely on multi-tasking OS to get concurrency.

    3. No Special code is needed to take advantage of multi-processor systems.

    Disadvantages:

    1. Process creation overhead.

    2. Potential overloading of computer.

    3. Not easy to cache anything.

    4. Not easy to share a single database.

    Datagrams

    Datagrams are bundles of information passed between machines. Once the datagram has been

    released to its intended target, there is no assurance that it will arrive or even that someone will be

    there to catch it. When the datagram is received, there is no assurance that it hasnt been damaged in

    transit or that whoever sent it is still there to receive a response. Applications that communicate via

    datagrams send and receive completely independent packets of information. These clients and servers

    do not have and do not need a dedicated point-to-point channel. The delivery of datagrams to their

    destinations is not guaranteed, nor is the order of their arrival. The underlying protocol is UDP which

    is a connectionless, unreliable and message oriented. UDP requires much less overhead than TCP/IP.

    UDP implementation has a limited queue for incoming datagrams. If our application cannot process

    these datagrams rapidly enough, they will be silently discarded. Neither the sender nor the receiver is

    notified when datagrams are dropped from a queue overflow.

    Java implements datagrams on top of the UDP protocol by using two classes in java.net:

    DatagramPacket: DataGram Packet object is the data container.

    DatagramSocket: It provides the mechanism used to send and receive the Datagram Packets.

    DatagramPacket

    Module 4 12

  • 7/28/2019 Network Computing

    13/19

    The DatagramPacket class represents a datagram packet. This class is a wrapper for an array

    of bytes from which data will be sent or into which data will be received. It also contains the address

    and port to which the packet will be sent. The object of this class is the data container.

    Constructors of DatagramPacket

    DatagramPacket(byte data[ ], int size)

    It specifies a buffer that will receive data, and the size of a packet. It is used for receiving data

    over a DatagramSocket.

    DatagramPacket(byte data[ ], int offset, int size)

    It allows us to specify an offset into the buffer at which data will be stored.

    DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)

    It specifies a target address and port, which are used by a DatagramSocket to determine where

    the data in the packet will be sent.

    DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)

    It is used to transmit packets beginning at the specified offset into the data.

    Methods of DatagramPacket

    InetAddress getAddress( )

    It returns the destination InetAddress, typically used for sending.

    int getPort( )

    It returns the port number.

    byte[ ] getData( )

    It returns the byte array of data contained in the datagram. It is used to retrieve data from the

    datagram after it has been received.

    int getLength( )

    It returns the length of the valid data contained in the byte array that would be returned from

    the getData( ) method. This typically does not equal the length of the whole byte array.

    DatagramSocket

    This class represents a socket for sending and receiving datagram packets. The actual sending

    and receiving tasks are accomplished with the DatagramSocket class, which creates a UDP socket.

    Constructors of DatagramSocket

    DatagramSocket( )

    It creates a socket at an unused short lived port, generally used for client applications.

    DatagramSocket(int port)

    It creates a socket and specifies a particular port, which is useful for server applications.

    Module 4 13

  • 7/28/2019 Network Computing

    14/19

    DatagramSocket(int port, InetAddress localAddr)

    It creates a socket bound to a port on machines with multiple IP interfaces. It is used to send

    and listen for datagrams from one of the IP addresses assigned to the machine. On such a

    host, datagrams sent to any of the machine's IP addresses are received by a DatagramSocket

    created with the first two constructors, while the last constructor obtains only datagrams sent

    to the specific IP address.

    Methods of DatagramSocket

    public void send(DatagramPacket p) throws IOException;

    This method is used to send properly addressed DatagramPacket instances.

    public synchronized void receive(DatagramPacket p) throws IOException;

    The transmitted datagram can be received using this method. The receive( ) method blocks

    until a datagram is received.

    public synchronized void setSoTimeout(int timeout) throws SocketException;

    Our application cannot expect receive( ) ever to return unless a timeout is enabled. It is

    achieved by this method. The timeout is a value in milliseconds. If set to 0, the receive( )

    method exhibits an infinite timeout, the default behaviour. When greater than zero, a

    subsequent receive( ) method invocation waits only the specified timeout before an

    InterruptedIOException is thrown.

    public synchronized void close();

    After communications through the UDP socket are completed, that socket should be closed

    using this method.

    IP Multicasting

    Internet Protocol (IP) is the means by which all information on the Internet is transmitted.

    UDP datagrams are encapsulated within IP packets to send them to the appropriate machines on the

    network. Most uses of IP involve unicasting: sending a packet from one host to another. IP includes

    the capability to multicast. With multicasting, a message is addressed to a targeted set of hosts. One

    message is sent, and the entire group can receive it.

    Multicasting is particularly suited to high-bandwidth applications, such as sending video and

    audio over the network, because a separate transmission need not be established. Other possible

    applications include chat sessions, distributed data storage, and online, interactive games. multicasting

    can be used by a client searching for an appropriate server on the network; it can send a multicastrequest, and any listening servers could contact the client to begin a transaction.

    MulticastSocket class of the java.net package is used for sending and receiving IP multicast

    packets. MulticastSocket allows you to send or receive UDP datagrams that use multicast IP.

    The MulticastSocket( ) constructor creates a multicast socket.

    Then we must create an appropriately formed DatagramPacket addressed to a multicast group.

    After it is created, the datagram can be sent with the send( ) method, which requires a TTL

    (time to live) value.

    The receive( ) method is used just as with the DatagramSocket to obtain incoming messages

    Module 4 14

  • 7/28/2019 Network Computing

    15/19

    To support IP multicasting, a certain range of IP addresses is set aside solely for this purpose.

    These IP addresses are class D addresses, those within the range of 224.0.0.0 and 239.255.255.255.

    Each of these addresses is referred to as a multicast group. Any IP packet addressed to that group is

    received by any machine that has joined that group. Group membership is dynamic and changes over

    time. When a machine joins a multicast group, it begins accepting messages sent to that IP multicast

    address. To send a message to a group, a host need not be a member of that group.

    Multicast groups are mapped to hardware addresses on interface cards. Thus, IP multicast

    datagrams that reach an uninterested host can usually be rapidly discarded by the interface card.

    Multicasting has its limitations, particularly the task of routing multicast packets throughout

    the Internet. Internet Group Management Protocol (IGMP), is used to manage memberships in a

    multicast group. A router that supports multi-casting can use IGMP to determine if local machines are

    subscribed to a particular group and whether to forward on a multicast packet.

    RMI ( 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. It allows us to build distributedapplications. The Java Remote Method Invocation Application Programming Interface (API), or Java

    RMI, is a Java application programming interface that performs the object-oriented equivalent of

    remote procedure calls (RPC).

    RMI functionality comes in the package java.rmi. RMI allows us to create Java objects

    whose methods can be invoked by the Virtual Machine on a different computer. Although these

    objects live and process on a different computer, they are used on the remote machine just like any

    local object.

    Any object that can be called remotely must implement the Remote interface. We must create

    a new interface for our object, that interface must extend Remote. The new interface will contain all

    of the methods that can be called remotely.

    Steps:

    1. Define an interface that extends the Remote interface. Each method of this new interface must

    declare that it will throw a RemoteExecption.

    2. Define a class that implements the interface. Because the new interface extends Remote, this

    fulfills the requirements for making the new class a remote object. The class must provide a

    means to marshal references to the instances of the class.

    3. Generate the stubs and skeletons that are needed for the remote implementations by using the

    rmic program.

    4. Create a client program that will make RMI calls to the server.

    5. Start the Registry and run your remote server and client.

    A Simple Client/Server Application Using RMI

    The following example shows a simple client/server application by using RMI. The server

    receives a request from a client, processes it, and returns a result.

    Enter and Compile the Source Code

    Module 4 15

  • 7/28/2019 Network Computing

    16/19

    AddServerIntf.java

    import java.rmi.*;

    public interface AddServerIntf extends Remote {

    double add(double d1, double d2) throws RemoteException;

    }

    AddServerIntf.java, defines the remote interface that is provided by the server. It contains

    one method that accepts two double arguments and returns their sum. All remote interfaces must

    extend the Remote interface, which is part of java.rmi. Remote defines no members. Its purpose is

    simply to indicate that an interface uses remote methods. All remote methods can throw a

    RemoteException.

    AddServerImpl.java

    import java.rmi.*;

    import java.rmi.server.*;

    public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf {

    public AddServerImpl() throws RemoteException {

    }

    public double add(double d1, double d2) throws RemoteException {

    return d1 + d2;

    }

    }

    AddServerImpl.java, implements the remote interface. The implementation of the add( )

    method is done here. All remote objects must extend UnicastRemoteObject, which provides the

    functionality that is needed to make objects available from remote machines.

    AddServer.java

    import java.net.*;

    import java.rmi.*;

    public class AddServer {

    public static void main(String args[]) {

    try {

    AddServerImpl addServerImpl = new AddServerImpl();

    Naming.rebind("AddServer", addServerImpl);

    }

    catch(Exception e) {

    Module 4 16

  • 7/28/2019 Network Computing

    17/19

    System.out.println("Exception: " + e);

    }

    }

    }

    AddServer.java, contains the main program for the server machine. Its primary function is to

    update the RMI registry on that machine. This is done by using the rebind( ) method of the Naming

    class (found in java.rmi). That method associates a name with an object reference. The first argument

    to the rebind( ) method is a string that names the server as AddServer. Its second argument is a

    reference to an instance of AddServerImpl.

    AddClient.java

    import java.rmi.*;

    public class AddClient {

    public static void main(String args[]) {

    try {

    String addServerURL = "rmi://" + args[0] + "/AddServer";

    AddServerIntf addServerIntf = (AddServerIntf)Naming.lookup(addServerURL);

    System.out.println("The first number is: " + args[1]);

    double d1 = Double.valueOf(args[1]).doubleValue();

    System.out.println("The second number is: " + args[2]);

    double d2 = Double.valueOf(args[2]).doubleValue();

    System.out.println("The sum is: " + addServerIntf.add(d1, d2));

    }

    catch(Exception e) {

    System.out.println("Exception: " + e);

    }

    }

    }

    AddClient.java, implements the client side of this distributed application. AddClient.java

    requires three command line arguments. The first is the IP address or name of the server machine. The

    second and third arguments are the two numbers that are to be summed.

    After we enter all the code, use javac to compile the four source files that we created.

    Generate Stubs and Skeletons

    Module 4 17

  • 7/28/2019 Network Computing

    18/19

    A stub is a Java object that resides on the client machine. Its function is to present the same

    interfaces as the remote server. Remote method calls initiated by the client are actually directed to the

    stub. The stub works with the other parts of the RMI system to formulate a request that is sent to the

    remote machine.

    A skeleton is a Java object that resides on the server machine. It works with the other parts of

    the RMI system to receive requests, perform deserialization, and invoke the appropriate code on theserver. If a response must be returned to the client, the process works in reverse.

    To generate stubs and skeletons, you use a tool called the RMI compiler, which is invoked from the

    command line,

    rmic AddServerImpl

    This command generates two new files: AddServerImpl_Skel.class (skeleton) and

    AddServerImpl_Stub.class (stub). When using rmic, be sure that CLASSPATH is set to include the

    current directory.

    Install Files on the Client and Server Machines

    Copy AddClient.class, AddServerImpl_Stub.class, and AddServerIntf.class to a directory on

    the client machine.

    Copy AddServerIntf.class, AddServerImpl.class, AddServerImpl_Skel.class,

    AddServerImpl_Stub.class, and AddServer.class to a directory on the server machine.

    Start the RMI Registry on the Server Machine

    The Java 2 provides a program called rmiregistry, which executes on the server machine. It

    maps names to object references. First, check that the CLASSPATH environment variable includes

    the directory in which our files are located. Then, start the RMI Registry from the command line.

    start rmiregistry

    A new window is created which must be left open until we are done with the RMI example.

    Start the Server

    The server code is started from the command line

    java AddServer

    Start the Client

    The AddClient software requires three arguments: the name or IP address of the server

    machine and the two numbers that are to be summed together.

    java AddClient localhost 8 9

    or

    Module 4 18

  • 7/28/2019 Network Computing

    19/19

    java AddClient 11.12.13.14 8 9

    In the first line, the name of the server is provided. The second line uses its IP address (11.12.13.14).

    Working

    The application begins by forming a string that follows the URL syntax. This URL uses thermi protocol. The string includes the IP address or name of the server and the string AddServer. The

    program then invokes the lookup( ) method of the Naming class. This method accepts one argument,

    the rmi URL, and returns a reference to an object of type AddServerIntf. All remote method

    invocations can then be directed to this object.

    The program continues by displaying its arguments and then invokes the remote add( ) method. The

    sum is returned from this method and is then printed.

    Output

    The first number is: 8

    The second number is: 9

    The sum is: 17.0

    **********************************************************************************

    Module 4 19