410 likes | 695 Views
Network Programming with Java – Socket Programming in Java-Client Sockets-Server Sockets- Secure Server Sockets- TCP/IP Programming with Java – Datagrams, IP multicasting, Remote Method Invocation. Java Network Programming. Java.net package defines the classes needed for networking
E N D
Network Programming with Java – Socket Programming in Java-Client Sockets-Server Sockets- Secure Server Sockets- TCP/IP Programming with Java – Datagrams, IP multicasting, Remote Method Invocation.
Java Network Programming • Java.net package defines the classes needed for networking • At the core of Java’s networking support is the concept of a socket. • A socket identifies an endpoint in a network.
Java Network Programming • Socket communication takes place via a protocol. • Internet Protocol (IP) is a low-level routing protocol that breaks data into small packets and sends them to an address across a network, which does not guarantee to deliver said packets to the destination. • Transmission Control Protocol (TCP) is a higher-level protocol that manages to robustly string together these packets, sorting and retransmitting them as necessary to reliably transmit data. • A third protocol, User Datagram Protocol (UDP), sits next to TCP and can be used directly to support fast, connectionless, unreliable transport of packets.
Java Network Programming • Once a connection has been established, a higher-level protocol ensues, which is dependent on which port you are using. • TCP/IP reserves the lower 1,024 ports for specific protocols. • Many of these will seem familiar to you if you have spent any time surfing the Internet. Port number 21 is for FTP; 23 is for Telnet; 25 is for e-mail; • It is up to each protocol to determine how a client should interact with the port.
Java Network Programming • A key component of the Internet is the address. Every computer on the Internet has one. • An Internet address is a number that uniquely identifies each computer on the Net. • Originally, all Internet addresses consisted of 32-bit values, organized as four 8-bit values. This address type was specified by IPv4 (Internet Protocol, version 4). • Anew addressing scheme, called IPv6 (Internet Protocol, version 6) has come into play. IPv6 uses a 128-bit value to represent an address, organized into eight 16-bit chunks. • Although there are several reasons for and advantages to IPv6, the main one is that it supports a much larger address space than does IPv4.
Java Network Programming • To provide backward compatibility with IPv4, the low-order 32 bits of an IPv6 address can contain a valid IPv4 address. • Thus, IPv4 is upwardly compatible with IPv6. • Fortunately, when using Java, you won’t normally need to worry about whether IPv4 or IPv6 addresses are used because Java handles the details for you.
Java Network Programming • Just as the numbers of an IP address describe a network hierarchy, the name of an Internet address, called its domain name, describes a machine’s location in a name space. • For example, www.osborne.com is in the COM domain (commercial sites); it is called osborne (after the company name), and www identifies the server for web requests. • An Internet domain name is mapped to an IP address by the Domain Naming Service(DNS). • This enables users to work with domain names, but the Internet operates on IP addresses.
Java Network Programming • The InetAddress class is used to encapsulate both the numerical IP address and the domain name for that address. • You interact with this class by using the name of an IP host, which is more convenient and understandable than its IP address. • The InetAddress class hides the number inside. • The InetAddress class has no visible constructors. • To create an InetAddress object, you have to use one of the available factory methods. • Factory methods are merely a convention whereby static methods in a class return an instance of that class.
Java Network Programming • The getLocalHost( ) method simply returns the InetAddress object that represents the local host. • The getByName() method returns an InetAddress for a host name passed to it. • The getAllByName() factory method returns an array of InetAddresses that represent all of the addresses that a particular name resolves to.
TCP/IP Programming • 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 Java’s I/O system to other programs that may reside either on the local machine or on any other machine on the Internet. • The creation of a Socket object implicitly establishes a connection between the client and server. • There are no methods or constructors that explicitly expose the details of establishing that connection.
TCP/IP Programming • There are two kinds of TCPsockets in Java. One is for servers, and the other is for clients. • The ServerSocket class is designed to be a “listener,” which waits for clients to connect before doing anything. • Thus, ServerSocket is for servers. • The Socket class is for clients. • It is designed to connect to server sockets and initiate protocol exchanges.
TCP/IP Programming • You can gain access to the input and output streams associated with a Socket by use of the getInputStream( ) and getOuptutStream( ) methods. • Each can throw an IOException if the socket has been invalidated by a loss of connection.
TCP/IP Programming • The ServerSocket class is used to create servers that listen for either local or remote client programs to connect to them on published ports. • ServerSockets are quite different from normal Sockets. • When you create a ServerSocket, it will register itself with the system as having an interest in client connections. • The constructors for ServerSocket reflect the port number that you want to accept connections on and, optionally, how long you want the queue for said port to be. • The queue length tells the system how many client connections it can leave pending before it should simply refuse connections. The default is 50
TCP/IP Programming • 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.
TCP/IP Programming - Datagrams • TCP/IP-style networking is appropriate for most networking needs. • It provides a serialized, predictable, reliable stream of packet data. • TCP includes many complicated algorithms for dealing with congestion control on crowded networks, as well as pessimistic expectations about packet loss. • This leads to a somewhat inefficient way to transport data. Datagrams provide an alternative.
TCP/IP Programming - 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. • Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a response.
TCP/IP Programming - Datagrams • Java implements datagrams on top of the UDP protocol by using two classes: the DatagramPacket object is the data container, while the DatagramSocket is the mechanism used to send or receive the DatagramPackets. • DatagramSocket defines four public constructors. They are shown here: • DatagramSocket( ) throws SocketException • DatagramSocket(int port) throws SocketException • DatagramSocket(int port, InetAddressipAddress) throws SocketException • DatagramSocket(SocketAddress address) throws SocketException
TCP/IP Programming - Datagrams • DatagramSocket defines many methods. Two of the most important are send( ) and receive( ) • void send(DatagramPacketpacket) throws IOException • void receive(DatagramPacketpacket) throws IOException • The send( ) method sends packet to the port specified by packet. • The receive method waits for a packet to be received from the port specified by packet and returns the result.
TCP/IP Programming - Datagrams • DatagramPacket defines several constructors. Four are shown here: • DatagramPacket(bytedata[ ], int size) • DatagramPacket(bytedata[ ], int offset, int size) • DatagramPacket(byte data[], int size, InetAddressipAddress, int port) • DatagramPacket(byte data[], int offset, int size, InetAddressipAddress, int port) • The first constructor specifies a buffer that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket. • The second form allows you to specify an offset into the buffer at which data will be stored. • The third form specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent. • The fourth form transmits packets beginning at the specified offset into the data.
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. • This is an important feature, because it allows you to build distributed applications.
A Simple Client/Server Application Using RMI • The server receives a request from a client, processes it, and returns a result. • In this example, the request specifies two numbers. The server adds these together and returns the sum.
A Simple Client/Server Application Using RMI • Step One: Enter and Compile the Source Code • This application uses four source files. The first file, 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.
A Simple Client/Server Application Using RMI • Step One: Enter and Compile the Source Code import java.rmi.*; public interface AddServerIntf extends Remote { double add(double d1, double d2) throws RemoteException; }
A Simple Client/Server Application Using RMI • Step One: Enter and Compile the Source Code • The second source file, AddServerImpl.java, implements the remote interface. • All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.
A Simple Client/Server Application Using RMI 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; } }
A Simple Client/Server Application Using RMI • The third source file, 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.
A Simple Client/Server Application Using RMI • The fourth source file, 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.
A Simple Client/Server Application Using RMI • The application begins by forming a string that follows the URL syntax. • This URL uses the rmi 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.
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); } } }
A Simple Client/Server Application Using RMI • Step Two: Generate a Stub • 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 Simple Client/Server Application Using RMI • To generate a stub, you use a tool called the RMI compiler, which is invoked from the command line, • rmic AddServerImpl
A Simple Client/Server Application Using RMI • Step Three: 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_ • Stub.class, and AddServer.class to a directory on the server machine.
A Simple Client/Server Application Using RMI • Step Four: Start the RMI Registry on the Server Machine • Java SE 6 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 your files are located. • Then, start the RMI Registry from the command line, as • start rmiregistry • When this command returns, you should see that a new window has been created. • You need to leave this window open until you are done experimenting with the RMI example.
A Simple Client/Server Application Using RMI • Step Five: Start the Server • The server code is started from the command line, as : • java AddServer • Recall that the AddServer code instantiates AddServerImpl and registers that object with the name “AddServer”.
A Simple Client/Server Application Using RMI • Step Six: Start the Client • The AddClient software requires three arguments: the name or IPaddress of the server machine and the two numbers that are to be summed together.