Chapter 6 Networking In Java
Introduction
– Java provides a number of built-in networking capabilities that make
it easy to develop Internet-based and web-based applications.
– The term network programming refers to writing programs that
execute across multiple devices (computers), in which the devices are
all connected to each other using a network.
– Through the classes in [Link] Java programs can use TCP or
UDP to communicate over the Internet.
– Through classes from [Link], Java offers
• Stream-based communications that enable applications to view
networking as streams of data as if it were file I/O. (TCP)
• Packet-based communications for transmitting individual
packets of information—commonly used to transmit data
images, audio and video over the Internet. (UDP)
– Socket - connecting to other computers
– Is simply a software construct that represents one endpoint of a
connection.
– A socket is a host-local, application-created, OS-controlled interface
(a “door”) into which application process can both send and receive
messages to/from another application process.
– When connecting to another computer you use a ‘socket’.
– When opening a file you uniquely identify it by its file name.
– When connecting to a computer you uniquely identify it with its IP
number.
– There are two types of Sockets:
Stream Socket
– With stream sockets, a process establishes a connection to another
process.
– While the connection is in place, data flows between the processes in
continuous streams.
– Stream sockets are said to provide a connection-oriented service.
– The protocol used for transmission is the popular TCP (Transmission
Control Protocol).
Datagram Socket
– With datagram sockets, individual packets of information are
transmitted.
– The protocol —UDP, the User Datagram Protocol—is a
connectionless service and does not guarantee that packets arrive in
any particular order.
– Ports - connecting to programs on other computer over a network
– Using a unique number we can identify a computer to connect to
– However, computers have many programs running on them
– We identify which program to communicate with by using a port
number.
– Common networking programs (such as telnet, ftp and WWW
services) are always on the same port. These ports are called “well
known”.
– Telnet is on port 23, FTP on port 21, WWW services are on port 80,
etc.
Socket-programming using TCP
Socket: a door between application process and end-end-transport protocol (UDP or
TCP)
TCP service: reliable transfer of bytes from one process to another
Client must contact server
server process must first be running
server must have created socket (door) that welcomes client’s contact
Client contacts server by:
creating client-local TCP socket
specifying IP address, port number of server process
When client creates socket: client TCP establishes connection to server TCP
When contacted by client, server TCP creates new socket for server process to
communicate with client
allows server to talk with multiple clients
source port numbers used to distinguish clients
Client/server socket interaction: TCP
Socket programming with UDP
UDP: no “connection” between client and server
• no handshaking
• sender explicitly attaches IP address and port of destination to each packet
• server must extract IP address, port of sender from received packet
• UDP: transmitted data may be received out of order, or lost
Client/server socket interaction: UDP
Example – Client
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader([Link]()));
[Link]("Received string: '");
while (![Link]()) {}
[Link]([Link]()); // Read one line and output it
[Link]("'\n");
[Link]();
catch(Exception e) {
[Link]("Oops! It didn't work!\n");
}
Example – Server
import [Link].*;
import [Link].*;
import [Link].*;
class Server {
public static void main(String args[]) {
String data = "This is a test msg";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = [Link]();
[Link]("Server has connected!\n");
PrintWriter out = new PrintWriter([Link](), true);
[Link]("Sending string: '" + data + "'\n");
[Link](data);
[Link](); [Link](); [Link]();
catch(Exception e) {
[Link]("Oops! It didn't work!\n");
}
Socket Methods
public ServerSocket(int port) throws IOException
Attempts to create a server socket bound to the specified port. An exception occurs if the port is already b
public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies how many incoming clients to store in
public ServerSocket(int port, int backlog, InetAddress address) throws IOException
Similar to the previous constructor, the InetAddress parameter specifies the local IP address to bind to. Th
servers that may have multiple IP addresses, allowing the server to specify which of its IP addresses to ac
public ServerSocket() throws IOException
Creates an unbound server socket. When using this constructor, use the bind() method when you are ready
public int getLocalPort()
Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port
server find a port for you.
public Socket accept() throws IOException
Waits for an incoming client. This method blocks until either a client connects to the server on the specifi
assuming that the time-out value has been set using the setSoTimeout() method. Otherwise, this method b
public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during the accept().
public void bind(SocketAddress host, int backlog)
Binds the socket to the specified server and port in the SocketAddress object. Use this method if you insta
no-argument constructor.
public void connect(SocketAddress host, int timeout) throws IOException
This method connects the socket to the specified host. This method is needed only when you instantiated
constructor.
public InetAddress getInetAddress()
This method returns the address of the other computer that this socket is connected to.
public int getPort()
Returns the port the socket is bound to on the remote machine.
public int getLocalPort()
Returns the port the socket is bound to on the local machine.
public SocketAddress getRemoteSocketAddress()
Returns the address of the remote socket.
public InputStream getInputStream() throws IOException
Returns the input stream of the socket. The input stream is connected to the output stream of the remote so
public OutputStream getOutputStream() throws IOException
Returns the output stream of the socket. The output stream is connected to the input stream of the remote
public void close() throws IOException
Closes the socket, which makes this Socket object no longer capable of connecting again to any server
InetAddess Class Methods
static InetAddress getByAddress(byte[] addr)
Returns an InetAddress object given the raw IP address .
static InetAddress getByAddress(String host, byte[] addr)
Create an InetAddress based on the provided host name and IP address.
static InetAddress getByName(String host)
Determines the IP address of a host, given the host's name.
String getHostAddress()
Returns the IP address string in textual presentation.
String getHostName()
Gets the host name for this IP address.
static InetAddress InetAddress getLocalHost()
Returns the local host.
String toString()
Converts this IP address to a String.
Remote Method Invocation(RMI)
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.
RMI allows a Java program on one machine to invoke a method on a
remote object.
Basic RMI Process
Marshalling Parameters:- Is serializing parameters .
Unmarshalling Parameters:- Is deserializing parameters .
• The “client object” has to find the object
• Do this by looking it up in a registry
• The client object then has to marshal the parameters (prepare
them for transmission)
• The server object has to unmarshal its parameters, do its
computation, and marshal its response
• The client object has to unmarshal the response
The General RMI Architecture
The server must first bind its name to the registry
The client lookup the server name in the registry to establish remote
references.
The Stub serializing the parameters to skeleton, the skeleton invoking the
remote method and serializing the result back to the stub.
The Stub and Skeleton
– A client invokes a remote method, the call is first forwarded to stub.
– The stub is responsible for sending the remote call over to the server-
side skeleton
– The stub opening a socket to the remote server, marshaling the object
parameters and forwarding the data stream to the skeleton.
– A skeleton contains a method that receives the remote calls, un
marshals the parameters, and invokes the actual remote object
implementation.
Support for the Interface
• Stub/Skeleton layer
– Responsible for managing the remote object interface between the
client and server
– Stubs and skeleton code generated by using the rmic compiler, rmic -
v1.2 NameOfImplementation Class for stub and skeleton incorporated
in RRL.
• Remote reference layer
– Responsible for managing the "liveliness" of the remote objects
– Manages the communication between the client/server and virtual
machines
Terminology
– A remote object is an object on another computer
– The client object is the object making the request (sending a message
to the other object)
– The server object is the object receiving the request
– As usual, “client” and “server” can easily trade roles (each can make
requests of the other)
– The rmiregistry is a special server that looks up objects by name
– rmic is a special compiler for creating stub (client) and skeleton
(server) classes
Steps for Developing a RMI System
1. Create the interface
2. Define a class that implements this interface
3. Create the server process.
4. Create the client process.
5. Compile all “.java” files.
6. Compile the implementation class with the rmic.
7. Start the RMI registry.
8. Open a new window and run the server.
9. Open a third window and run the client.
Create interface: Hello
import [Link].*;
public interface Hello extends Remote
public String getGreeting() throws RemoteException;
Define implementation class: HelloImpl
import [Link].*;
import [Link].*;
public class HelloImpl extends UnicastRemoteObject implements Hello
public HelloImpl() throws RemoteException{
//No action needed here.
public String getGreeting() throws RemoteException
return ("Hello there!");
Create server process:
import [Link].*;
public class HelloServer
{
private static final String HOST = "localhost";
public static void main(String[] args) throws Exception
//Create a reference to an implementation object...
HelloImpl temp = new HelloImpl();
//Create the string URL holding the object's name...
String rmiObjectName = "rmi://" + HOST + "/Hello";
//(Could omit host name here, since 'localhost’ would be assumed by default.)
//'Bind' the object reference to the name...
[Link](rmiObjectName,temp);
//Display a message so that we know the process has been completed...
[Link]("Binding complete...\n");
Create client process:
import [Link].*;
public class HelloClient
private static final String HOST = "localhost";
public static void main(String[] args)
try
{
//Obtain a reference to the object from the registry and typecast it into the appropriate
type...
Hello greeting = (Hello)[Link]("rmi://” + HOST + "/Hello");
//Use the above reference to invoke the remote object's method...
[Link]("Message received: “ + [Link]());
catch(ConnectException conEx)
[Link]("Unable to connect to server!");
[Link](1);
catch(Exception ex)
[Link]();
[Link](1);
Compilation and Execution
1. javac *.java
2. rmic HelloImpl
3. Rmiregistry
4. java HelloServer
5. java HelloClient
Client side files:
[Link], [Link] and HelloImpl_Stub.class
Server side files:
[Link], [Link] and [Link]