Chapter 6 Networking in Java

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

1

METTU UNIVERSITY
FACULTY OF ENGINEERING & TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE
Java programming course
Chapter-6
Networking in Java

1 By: Naol G.
Introduction: What Is a Network?
 A network is a collection of devices that share a common
communication protocol and a common communication medium
(such as network cables, dial-up connections, and wireless links).
 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.

2 By Naol G.(MSc.)
Client-Server Computing
 At a basic level, network-based systems consist of a server ,
client , and a media for communication as shown in next
slide figure.
 A computer running a program that makes a request for services
is called client machine.
 A computer running a program that offers requested services
from one or more clients is called server machine.
 The media for communication can be wired or wireless
network.

3 By Naol G.(MSc.)
Elements of Client -Server Computing

Client, Server, and Network

Client
Server
Network

Client machine
Server machine

4 By Naol G.(MSc.)
Hosts Identification
 Every computer on the Internet is identified by a unique, 4-byte
IP address . This is typically written in dotted octet format like
128.250.25.158 where each byte is an unsigned value between 0
and 255.
 This representation is clearly not user-friendly because it does
not tell us anything about the content and then it is difficult to
remember. Hence, IP addresses are mapped to names like
www.yahoo.com or www.google.com, which are easier to remember.
 Internet supports name servers that translate these names to IP
addresses. Domain Naming Service (DNS) maps names to
numbers.

5 By Naol G.(MSc.)
IP Addresses and Java
 Java has a class java.net.InetAddress which
encapsulate numerical/domain name of IP addresses.
 InetAddress class can:
 Performs name lookup (converting a host name into an IP
address).
 Performs reverse lookup (converting the address into a host
name).
 InetAddress class has no visible constructor.
 To create InetAddress object, you have to use one its available
methods.

6 By Naol G.(MSc.)
Some useful methods: InetAddress
 public String getHostName()
 Return the host name (e.g.: “www.sun.com”) of IP address.
 String getHostAddress()
 Returns string format of the address (e.g.: “192.18.97.241”)
 InetAddress[] getAllByName(String hostName)
 boolean equals(Object obj)
 byte[] getByAddress() returns the IP address in byte format (as
opposed to dotted decimal notation)
 InetAddress getByName(String hostName)
 InetAddress getLocalHost() returns the instance of InetAddress
containing local host name and address.

7 By Naol G.(MSc.)
Example

Output:

8 By Naol G.(MSc.)
Service Ports
 Each service offered by a computer is uniquely identified by a port
number. Each Internet packet contains both the destination host
address and the port number on that host to which the
message/request has to be delivered.
 That is, IP address can be thought of as a house address when a letter is
sent via post/snail mail and port number as the name of a specific
individual to whom the letter has to be delivered.
 Port numbers range from 0 to 65,535 (16-bit).Ports 0 - 1024 are called
well-known ports. They are reserved for use by well-known services:
 20, 21: FTP
 23: TELNET
 25: SMTP
 110: POP3
 80: HTTP

9 By Naol G.(MSc.)
What is a Socket ?
 A socket is an endpoint of a two-way communication link between two
programs running on the network.
 Network communication using Sockets is very much similar to
performing file I/O.
 In fact, socket handle is treated like file handle.
 The streams used in file I/O operation are also applicable to
socket-based I/O.
 Socket-based communication is independent of a programming
language used for implementing it.
 That means, a socket program written in Java language can
communicate to a program written in non-Java (say C or C++)
socket program.

10 By Naol G.(MSc.)
 Types of socket in java: …
 A) Stream sockets enable a process to establish a connection
with another process. While the connection is in place, data
flows between the processes in continuous streams.
 Stream sockets provide a connection-oriented service. The protocol used
for transmission is the popular TCP (Transmission Control Protocol).
Provides reliable , in-order byte-stream service
 B) Datagram sockets transmit individual packets of information.
 This is typically not appropriate for use by everyday programmers
because the transmission protocol is UDP (User Datagram Protocol).
 UDP provides a connectionless service. A connectionless service does
not guarantee that packets arrive at the destination in any particular
order.

11 By Naol G.(MSc.)

 The java.net package provides support for the two common
network protocols:
1. TCP communication:
 Socket
 ServerSocket
2. UDP communication:
 DatagramPacket
 DatagramSocket
 MulticastSocket

12 By Naol G.(MSc.)
Socket Programming with TCP
 TCP (Transmission Control Protocol)
 A connection-oriented protocol.
 Allows reliable communication between two applications.
 Usually used over the Internet with IP as TCP/IP
 Be similar to making a telephone call
 The person placing the telephone call – client
 The person waiting for a call – server
 The java.net.ServerSocket and java.net.Socket classes are the only
two classes you will probably ever need to create a TCP/IP
connection between two computers.

13 By Naol G.(MSc.)
Sockets and Java Socket Classes
 A program can read from a socket or write to a socket as
simply as reading from a file or writing to a file.

 A socket is bound to a port number so that the TCP layer can


identify the application that data destined to be sent.

 Java.net package provides two classes:


1. Socket – for implementing a client
2. ServerSocket – for implementing a server

14 By Naol G.(MSc.)
Socket Communication
 A server (program) runs on a specific computer and has a
socket that is bound to a specific port.
 The server waits and listens to the socket for a client to make a
connection request.

Connection request Client


port

server

Fig. Client making connection request to server

15 By Naol G.(MSc.)

 If everything goes well, the server accepts the connection.
 Upon acceptance, the server gets a new socket bounds to a different
port. It needs a new socket (consequently a different port number) so
that it can continue to listen to the original socket for connection
requests while serving the connected client.
port

server

port
Client
port Connection

Fig. Session established with temporary ports used for two way communication

16 By Naol G.(MSc.)
Socket Operations
 There are four fundamental operations a socket performs. These
are:
 Connect to a remote machine
 Send data
 Receive data
 Close the connection
 The java.net.Socket class allows you to perform all four
fundamental socket operations
 Socket class represents the socket that both the client and server
use to communicate with each other.
 Connection is accomplished through the constructors.
 Each Socket object is associated with exactly one remote host. To
connect to a different host, you must create a new Socket object.

17 By Naol G.(MSc.)
Socket constructors
• Connect to a remote machine can be via following constructors:
 Socket(String host, int port) throws UnknownHostException, IOException
 Socket(InetAddress address, int port) throws IOException
 Socket(String host, int port, InetAddress localAddress, int localPort)
throws IOException
 Socket(InetAddress address, int port, InetAddress localAddress, int
localPort) throws IOException
 Sending and receiving data is accomplished with output and input streams.
 InputStream getInputStream() throws IOException
 Returns the input stream of the socket. The input stream is connected to the output
stream of the remote socket.
 OutputStream getOutputStream() throws IOException
 Returns the output stream of the socket. The output stream is connected to the input
stream of the remote socket
18 By Naol G.(MSc.)
Socket methods
 There are methods to return information about the socket:
 inetAddress getInetAddress()
 inetAddress getLocalAddress()
 int getPort() //Returns the port socket is bound to on the remote machine.
 int getLocalPort()//Returns the port socket is bound to on the local
machine.
 public void connect(SocketAddress host, int timeout)
 String toString()

 Finally, there's a method to close a socket.


 void close() throws IOException

19 By Naol G.(MSc.)
ServerSocket methods
1. 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 number in a constructor
and let the server find a port for you.
2. public Socket accept() throws IOException
 Waits for an incoming client.
 This method blocks until either a client connects to the server on the
specified port or the socket times out, assuming that the time-out value has
been set using the setSoTimeout() method.
3. public void setSoTimeout(int timeout)
 Sets the time-out value for how long the server socket waits for a client
during the accept().
4. 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 instantiated the ServerSocket using the no-argument
constructor.
20 By Naol G.(MSc.)
Socket Programming with TCP
 Server process must first be running (must have created a
socket). Recall that TCP is not connectionless.
 Client contacts the server by creating client-local socket
specifying IP address and port number of server process.
Client TCP establishes connection to server TCP.
 When contacted by client, server TCP creates a new socket
for server process to communicate with client.
 Allows server to talk with multiple clients

 Source port numbers used to distinguish clients

 From application viewpoint: TCP provides reliable, in-order


transfer of bytes (“pipe”) between client and server.

21 By Naol G.(MSc.)
Establishing a Simple Server Using Stream Sockets
Five steps to create a simple stream server in Java:
1. Open the Server Socket: Each client connection handled with a Socket
object. Server blocks until client connects.
ServerSocket server = new ServerSocket( PORT );
2.Wait for the Client Request.
Socket client = server.accept();
3.Create I/O streams for communicating to the client
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
4.Perform communication with client
Receive from client: String line = is.readUTF();
Send to client: os.writeUTF(“Hello\n”);
5. Close socket:
client.close();

22 By Naol G.(MSc.)
Establishing a Simple Client Using Stream Sockets
Four steps to create a simple stream client in Java:
1. Create a Socket Object:
Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
3. Perform I/O or communication with the server:
Receive data from the server: String line = is.readUTF();
Send data to the server: os.writeUTF(“Hello\n”);
4. Close the socket when done:
client.close();

23 By Naol G.(MSc.)
Example: Java server using TCP

24 By Naol G.(MSc.)
Example: Java client using TCP

25 By Naol G.(MSc.)
Output: first you must run server program..
Step-1: run TCPServer first Step-2: then run TCPClient

Step-3: finally check TCPServer after TCPClient connected:

26 By Naol G.(MSc.)
Socket Programming with UDP
 Datagram sockets transmit individual packets of information.
 This is typically not appropriate for use by everyday programmers because
the transmission protocol is UDP (User Datagram Protocol).
 UDP provides a connectionless service. A connectionless service
does not guarantee that packets arrive at the destination in any
particular order.
 With UDP, packets can be lost or duplicated. Significant extra
programming is required on the programmer’s part to deal with
these problems.
 UDP is most appropriate for network applications that do not
require the error checking and reliability of TCP.

27 By Naol G.(MSc.)
…UDP
 Under UDP there is no “connection” between the server and the client.
There is no “handshaking”.
 The sender explicitly attaches the IP address and port of the destination to
each packet.
 The server must extract the IP address and port of the sender from the
received packet.
 From an application viewpoint, UDP provides unreliable transfer of groups of
bytes (“datagrams”) between client and server.
 The java.net.DatagramPacket class –a data container
 The java.net.DatagramSocket class – a mechanism to send and
receive DatagramPackets.

 Sender does not wait for acknowledgements


 Arrival, arrival time & order is not guaranteed.
o So why use UDP if it unreliable?
o Two reasons: speed and overhead.
• Used when speed is essential, even in cost of reliability
– e.g. Streaming Media, Games, Internet Telephony, etc.
28 By Naol G.(MSc.)
DatagramPacket
 Data to be transferred is encapsulated in a unit called datagram.
 And in Java, DatagramPacket represents a datagram.
 We can create a DatagramPacket object by using one of the following
constructors:
 DatagramPacket(byte[] buf, int length)
 DatagramPacket(byte[] buf, int length, InetAddress address, int port)

 Note: the data must be in the form of an array of bytes.


 The first constructor: create a DatagramPacket to be received.
 The second constructor: creates a DatagramPacket to be sent.
 So you need to specify the address and port number of the destination host.
 The parameter length specifies the amount of data in the byte array to be used.

29 By Naol G.(MSc.)
DatagramSocket
 We use DatagramSocket to send and receive DatagramPackets.
 DatagramSocket represents a UDP connection between two computers
in a network.
 We use DatagramSocket for both client and server.
 There are no separate classes for client and server like TCP sockets.
 DatagramSocket constructors:
 DatagramSocket():
 create a client that binds to an random port.
 DatagramSocket(int port):
 create a server that binds to the specific port number, so the clients know
how to connect to.
 DatagramSocket(int port, InetAddress laddr)
 Binds server to specified IP address (in case it has multiple IP addresses).

30 By Naol G.(MSc.)
 The key methods of the DatagramSocket include:
 send(DatagramPacket p): sends a datagram packet.
 receive(DatagramPacket p): receives a datagram packet.
 setSoTimeout(int timeout): sets timeout in milliseconds,
limiting the waiting time when receiving data.
 If the timeout expires, a SocketTimeoutException is raised.
 close(): closes the socket.

31 By Naol G.(MSc.)
…UDP
Steps to Receive a Datagram packet - UDP
1. Create an array of bytes large enough to hold the data of the incoming packet.
byte[] buffer = new byte[1024];
2. A DatagramPacket object is instantiated using the array of bytes.
DatagramPacket packet =new DatagramPacket(buffer, buffer.length);
3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost
address, if necessary) on the localhost the socket will bind to.
int port = 1234;
DatagramSocket socket = new DatagramSocket(port);
4. The receive() method of the DatagramSocket class is invoked, passing in the
DatagramPacket object. This causes the thread to block until a datagram packet is received
or a time out occurs.

32 By Naol G.(MSc.)
…UDP
Steps to Send a Datagram packet - UDP
1. Create an array of bytes large enough to hold the data of the packet to be sent, and fill
the array with the data.
byte[] buffer = new byte[1024];
2. Create a new DatagramPacket object that contains the array of bytes, as well as the
server name and port number of the recipient.
int port = 1234;
InetAddress host =InetAddress.getByName(“www.mysite.com");
DatagramPacket packet =new DatagramPacket(buffer, buffer.length, host, port);
3. A DatagramSocket is instantiated, and it is specified which port (and specific localhost
address, if necessary) on the localhost the socket will bind to.
DatagramSocket socket = new DatagramSocket();
4. The send() method of the DatagramSocket class is invoked, passing in the
DatagramPacket object.

33 By Naol G.(MSc.)
Example: Java server using UDP

34 By Naol G.(MSc.)
Example: Java client using UDP

35 By Naol G.(MSc.)
Output:
 Step-1: run UDPServer: waiting to do on incoming data:

 Step-2: then, run UDPClient: waiting to insert data to be sent:

 Step-3: finally, after insert data and send (enter):

UDPServer

UDPClient

36 By Naol G.(MSc.)
Reading assignment:
……Serving Multiple Clients..…..

37 By Naol G.(MSc.)
Remote Method Invocation

38 By Naol G.(MSc.)
Introduction
 What is distributed system:
 A distributed system is a software system in which components

located on networked computers communicate and coordinate


their actions by passing messages.

 The components interact with each other in order to achieve

a common goal.

39 By Naol G.(MSc.)
Organization Distributed System
• To support heterogeneous computers and networks and to provide a single-system view, a
distributed system is often organized by a means of a layer of software called middleware that
extends over multiple machines

A distributed system organized as middleware; note that the middleware layer


extends over multiple machines
40
RMI
 Provides a distributed object capability for Java applications.
 Allows a Java method to obtain a reference to a remote
object and invoke methods of the remote object nearly as
easily as if the remote object existed locally.

41 By Naol G.(MSc.)
RMI
 Provides a distributed object capability for Java applications.
Goal of RMI:
 Implement distributed objects. Have a program running on one
machine invoke a method belonging to an object whose execution is
performed on another machine.
 Reasons for Using RMI
 Some operations can be executed significantly faster on the remote
system than the local client computer.
 Specialized data or operations are available on the remote system that
cannot be replicated easily on the local system, for example, database
access.
 Simpler than programming our own TCP sockets and protocols.
 Java RMI allowed programmer to execute remote function class
using the same semantics as local functions calls.

42 By Naol G.(MSc.)
The General RMI Architecture
Remote Machine
1. The server must first bind its
name to the registry RMI Server
bind

2. The client lookup the server Registry


name in the registry to skeleton
establish remote references.
3. The Stub serializing the return call lookup

parameters to skeleton, the


skeleton invoking the remote stub
method and serializing the
result back to the stub. RMI Client

Local Machine

43 By Naol G.(MSc.)
The Stub and Skeleton
call

skeleton
Stub
RMI Client RMI Server
return

 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,
unmarshals the parameters, and invokes the actual remote
object implementation.

44 By Naol G.(MSc.)
RMI Registry
• The RMI registry is a simple server-side bootstrap naming
facility that allows remote clients to get a reference to a
remote object
• Servers name and register their objects to be accessed
remotely with the RMI Registry.
• Clients use the name to find server objects and obtain a
remote reference to those objects from the RMI Registry.
• A registry (using the rmiregistry command) is a separate
process running on the server machine.

45 By Naol G.(MSc.)
Steps for Developing an RMI System
1. Define the remote interface.
2. Develop the Server program.
3. Develop the client program.
4. Compile the Java source files and generate the client stubs
and server skeletons.
5. Start the RMI registry.
6. Start the remote server objects.
7. Run the client

46 By Naol G.(MSc.)
Step 1: Defining the Remote Interface

To create an RMI application, the first step is the defining of a remote
interface between the client and server objects.

 The client need to access methods in the remote objects on the server.
Therefore, an interface needs to be defined for both client and server.

import java.rmi.*;

public interface [yourInterface] extends Remote


{

In this interface which allows clients to access. Please be careful with
throws java.rmi.RemoteException because it has to be add in RMI file.

47 By Naol G.(MSc.)
Step 2: Develop the Server program
 Develop the remote object and its interface. The server is a simple unicast
remote server.
 Create server by extending java.rmi.server.UnicastRemoteObject.
The server uses the RMISecurityManager to protect its resources while
engaging in remote communication.

/* SampleServerImpl.java */
import java.rmi.*;
import java.rmi.server.*;
import java.rmi.registry.*;

public class [yourImplementationClass]extends UnicastRemoteObject


implements [yourInterface]
{
[yourImplementationClass]() throws RemoteException
{
super();
}

48 By Naol G.(MSc.)

 Implement the remote methods(all abstact method in the interface).
1. Declare the remote interfaces being implemented
2. Define the constructor for the remote object
3. Provide an implementation for each remote method in the remote interfaces

 The server must bind its name to the registry, the client will look up the server
name.
1. Create one or more instances of a remote object
[yourImplementationClass] objref= new [yourImplementationClass]();

2. Register at least one of the remote objects with the RMI remote object registry
(or some other naming service), for bootstrapping purposes
Use java.rmi.Naming class to bind the server name to
registry. for example the name call “SAMPLE-SERVER”.
Naming.rebind("SAMPLE-SERVER" , objref);
 In the main method of your server object, the RMI security manager is created and
installed.
System.setSecurityManager(new RMISecurityManager());
//set the security manager

49 By Naol G.(MSc.)
Step 3: Develop the client program
 In order for the client object to invoke methods on the server, it
must first look up the name of server in the registry. You use the
java.rmi.Naming class to lookup the server name.
 The server name is specified as URL in the from
( rmi://host:port/name )
 Default RMI port is 1099.
 The name specified in the URL must exactly match the name that
the server has bound to the registry. For example, the name is
“SAMPLE-SERVER”
 The remote method invocation is programmed using the remote
interface name (remoteObject) as prefix and the remote
method name (sum) as suffix.

50 By Naol G.(MSc.)
Step 4: Compile the Java source files & Generate
the client stubs and server skeletons
 Once the interface is completed, you need to generate stubs and
skeleton code. The RMI system provides an RMI compiler
(rmic) that takes your generated interface class and procedures
stub code on its self.
 To compile all the java class
 java *.java
 To generate stub and skeleton.
 rmic [Implementation className]

51 By Naol G.(MSc.)
Step 5: Start the RMI registry
 The RMI applications need install to Registry. And the Registry must start
manual by call rmiregisty.

 The rmiregistry us uses port 1099 by default.You can also bind


rmiregistry to a different port by indicating the new port number as :
rmiregistry <new port>

start rmiregistry

Steps 6 &7 Start the remote server objects & Run the client
 Once the Registry is started, the server can be started and will be
able to store itself in the Registry.

52 By Naol G.(MSc.)
1. Create the remote interface (Adder.java)

2. Provide the implementation of the remote interface


(AdderRemote.java)

53 By Naol G.(MSc.)
Create the server application

Create and run the client application

• create the stub and skeleton objects using the rmic tool. rmic AdderRemote
54
• Start
By Naolthe registry service by the rmiregistry tool: rmiregistry 9999
G.(MSc.)
55 By Naol G.(MSc.)
RMI vs. Socket-Level Programming
• RMI enables you to program at a higher level of abstraction. It hides the details
of socket server, socket, connection, and sending or receiving data. It even
implements a multithreading server under the hood, whereas with socket-level
programming you have to explicitly implement threads for handling multiple
clients.
• RMI applications are scalable and easy to maintain. You can change the RMI
server or move it to another machine without modifying the client program
except for resetting the URL to locate the server. (To avoid resetting the URL,
you can modify the client to pass the URL as a command-line parameter.)
• In socket-level programming, a client operation to send data requires a server
operation to read it. The implementation of client and server at the socket-level
is tightly synchronized.
• RMI clients can directly invoke the server method, whereas socket-level
programming is limited to passing values.
• Socket-level programming is very primitive. Avoid using it to develop
client/server applications. As an analogy, socket-level programming is like
programming in assembly language, while RMI programming is like
programming in a high-level language.
56
Read more….

 Exercises:
 Develop simple chat application using JavaFX based on socket
programming with TCP.
 Develop JavaFX application that retrieve student record stored
in the database using RMI.

57 By Naol G.(MSc.)
END

58 By Naol G.(MSc.)

You might also like