0% found this document useful (0 votes)
3 views60 pages

Interprocess Communication: The Application Program Interface (API) To UDP Provides A Abstraction (Concept)

The document discusses interprocess communication (IPC) through UDP and TCP protocols, detailing message passing, socket usage, and the characteristics of both communication methods. It explains synchronous and asynchronous communication, reliability, ordering, and provides Java API examples for implementing UDP and TCP servers and clients. Additionally, it covers issues related to datagram and stream communication, including message size, blocking, and timeouts.

Uploaded by

Phial
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views60 pages

Interprocess Communication: The Application Program Interface (API) To UDP Provides A Abstraction (Concept)

The document discusses interprocess communication (IPC) through UDP and TCP protocols, detailing message passing, socket usage, and the characteristics of both communication methods. It explains synchronous and asynchronous communication, reliability, ordering, and provides Java API examples for implementing UDP and TCP servers and clients. Additionally, it covers issues related to datagram and stream communication, including message size, blocking, and timeouts.

Uploaded by

Phial
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

INTERPROCESS COMMUNICATION

• Introduction
• The application program interface (API) to UDP
provides a message passing abstraction (concept);

• which is the simplest form of interprocess


communication.

• This enables a sending process to transmit a single


message to a receiving process.
INTERPROCESS COMMUNICATION
• The independent packets containing these messages
are called datagram.

• In the Java and UNIX APIs, the sender specifies the


destination using a socket –

• A socket is an indirect reference to a particular port


used by the destination process at

• a destination computer.
INTERPROCESS COMMUNICATION
• The application program interface (API) to TCP
provides the abstraction of

• a two-way stream between pairs of processes.

• The information communicated consists of a stream


of data items with no message boundaries.

• Streams provide a building block for producer-


consumer communication.
INTERPROCESS COMMUNICATION
• A producer and a consumer form a pair of processes
in which

• the role of the first is to produce data items and the


role of the second is to consume them.

• The data items sent by the producer to the consumer


are queued on arrival at the receiving host

• until the consumer is ready to receive them.


INTERPROCESS COMMUNICATION
• The API for the Internet protocols
• The characteristics of interprocess communication
• Message passing between a pair of processes can be
supported by

• two message communication operations,

• send and receive, defined in terms of destinations and


messages.
INTERPROCESS COMMUNICATION
• To communicate, one process sends a message (a
sequence of bytes) to a destination and

• another process at the destination receives the


message.
INTERPROCESS COMMUNICATION

• Synchronous and asynchronous communication


• In the synchronous form of communication, the
sending and receiving processes synchronize at every
message.

• In this case, both send and receive are blocking


operations.

• Whenever send is issued the sending process (or


thread) is blocked until the corresponding receive is
issued
INTERPROCESS COMMUNICATION

• Whenever receive is issued by a process (or thread), it


blocks until a message arrives.
INTERPROCESS COMMUNICATION
• In the asynchronous form of communication, the use
of the send operation is non blocking in that

• the sending process is allowed to proceed as soon as


the message has been copied to a local buffer, and

• the transmission of the message proceeds in parallel


with the sending process.

• The receive operation can have blocking and non-


blocking variants.
INTERPROCESS COMMUNICATION
• In the non-blocking variant, the receiving process
proceeds with its program after issuing a receive
operation,

• which provides a buffer to be filled in the


background,

• but it must separately receive notification that its


buffer has been filled.
INTERPROCESS COMMUNICATION

• Message destinations
• Messages are sent to (Internet address, local port)
pairs.
• A local port is a message destination within a
computer, specified as an integer.

• A port has exactly one receiver but can have many


senders.

• Processes may use multiple ports to receive messages


INTERPROCESS COMMUNICATION

• If the client uses a fixed Internet address to refer to a


service,

• then that service must always run on the same


computer for its address to remain valid.
INTERPROCESS COMMUNICATION
• Reliability
• As far as the validity property is concerned, a point-
to-point message service can be described as reliable

• if messages are guaranteed to be delivered despite a


‘reasonable’ number of packets being dropped or
lost.
• In contrast, a point-to-point message service can be
described as unreliable

• if messages are not guaranteed to be delivered in the


face of even a single packet dropped or lost.
INTERPROCESS COMMUNICATION
• Ordering
• Some applications require that messages be delivered
in sender order–

• that is, the order in which they were transmitted by


the sender.

• The delivery of messages out of sender order is


regarded as a failure by such applications.
INTERPROCESS COMMUNICATION
• Sockets
• Both forms of communication (UDP and TCP) use
the socket abstraction,

• which provides an endpoint for communication


between processes.

• Interprocess communication consists of transmitting a


message between a socket in one process and

• a socket in another process


INTERPROCESS COMMUNICATION
INTERPROCESS COMMUNICATION
• For a process to receive messages, its socket must be
bound to a local port and one of the

• Internet addresses of the computer on which it runs.

• Messages sent to a particular Internet address and


port number can be received only by

• a process whose socket is associated with that


Internet address and port number.
INTERPROCESS COMMUNICATION
• Java API for Internet addresses
• As the IP packets underlying UDP and TCP are sent
to Internet addresses, Java provides a class,

• InetAddress that represents Internet addresses.

• Users of this class refer to computers by Domain


Name System (DNS) hostnames.
INTERPROCESS COMMUNICATION
• For example, instances of InetAddress that contain
Internet addresses can be created

• by calling a static method of InetAddress, giving a


DNS hostname as the argument.

• The method uses the DNS to get the corresponding


Internet address.
INTERPROCESS COMMUNICATION
• For example, to get an object representing the Internet
address of the host whose

• DNS name is bruno.dcs.qmul.ac.uk, use:

• InetAddress aComputer = InetAddress.getByName


("bruno.dcs.qmul.ac.uk");
• Here is a simple program to illustrate the use of the
InetAddress class:
import java.net.*; catch(UnknownHostExcepti
import java.util.*; on e)
public class IPFinder {
{ System.out.println("Could
public static void main(String[] args) nt find "+host);
{ }
}
String host; }
Scanner input= new Scanner(System.in);
System.out.println("Enter host name:");
host=input.next();
try
{
InetAddress address =InetAddress.getByName(host);
System.out.println("IP address : " + address.toString());
}
INTERPROCESS COMMUNICATION
• UDP datagram communication
• A datagram sent by UDP is transmitted from a
sending process to a receiving process

• without acknowledgement.

• If a failure occurs, the message may not arrive.


INTERPROCESS COMMUNICATION
• A datagram is transmitted between processes when
one process sends it and another receives it.

• To send or receive messages a process must first


create a socket bound to

• an Internet address of the local host and a local port.


INTERPROCESS COMMUNICATION
• Unlike TCP/IP sockets, datagram sockets are
connectionless.

• That is to say, the connection between client and


server is not maintained throughout the duration of
the dialogue.

• Instead, each datagram packet is sent as an isolated


transmission whenever necessary.
INTERPROCESS COMMUNICATION
• Datagram (UDP) sockets provide a faster means of
transmitting data than TCP/IP sockets,

• but they are unreliable.

• Since the connection is not maintained between


transmissions,

• the server does not create an individual Socket


object for each client, as it does TCP/IP.
INTERPROCESS COMMUNICATION
• A further difference from TCP/IP sockets is that,
instead of a ServerSocket object,

• the server creates a DatagramSocket object, as does


each client when it wants to send datagram(s) to the
server.

• The final and most significant difference is that


DatagramPacket objects are created and sent at
both ends,

• rather than simple strings.


• The detailed steps required for the server:
– Create a DatagramSocket object
– Create a buffer for incoming datagrams
– Create a DatagramPacket object for the incoming
datagrams
– Accept an incoming datagram
– Accept the sender’s address and port
– Retrieve the data from the buffer
– Create the response datagram
– Send the response datagram
– Close the DatagramSocket
• Here is the complete program for the server.
import java.io.*;
import java.net.*;
import java.util.*;
/**
* This program demonstrates how to implement a UDP
server program.
*/
public class UDPEchoServer {
private DatagramSocket socket;
private List<String> listQuotes = new
ArrayList<String>();
private Random random;

public UDPEchoServer(int port) throws SocketException


{
socket = new DatagramSocket(port);
random = new Random();
}

public static void main(String[] args) {


if (args.length < 2) {
System.out.println("Syntax: QuoteServer
<file> <port>");
return;
}

String quoteFile = args[0];


int port = Integer.parseInt(args[1]);

try {
UDPEchoServer server = new
UDPEchoServer(port);
server.loadQuotesFromFile(quoteFile);
server.service();
} catch (SocketException ex) {
System.out.println("Socket error: " +
ex.getMessage());
} catch (IOException ex) {
System.out.println("I/O error: " +
ex.getMessage());
}
}

private void service() throws IOException {


while (true) {
DatagramPacket request = new
DatagramPacket(new byte[1], 1);
socket.receive(request);

String quote = getRandomQuote();


byte[] buffer = quote.getBytes();

InetAddress clientAddress =
request.getAddress();
int clientPort = request.getPort();

DatagramPacket response = new


DatagramPacket(buffer, buffer.length, clientAddress,
clientPort);
socket.send(response);
}
}

private void loadQuotesFromFile(String quoteFile) throws


IOException {
BufferedReader reader = new BufferedReader(new
FileReader(quoteFile));
String aQuote;
while ((aQuote = reader.readLine()) != null) {
listQuotes.add(aQuote);
}
reader.close();
}
private String getRandomQuote() {
int randomIndex =
random.nextInt(listQuotes.size());
String randomQuote =
listQuotes.get(randomIndex);
return randomQuote;
}
}
• //Type the following command to run the server program:
java UDPServer Quotes.txt 17
• The detailed steps required for the Client:
– Create a DatagramSocket object
– Create the outgoing datagram
– Send the datagram message
– Create a buffer for incoming datagrams
– Accept an incoming datagram
– Retrieve the data from the buffer
– Close the DatagramSocket
• Here is the complete program for the client.
import java.io.*;
import java.net.*;
/* This program demonstrates how to implement a
UDP client program. */

public class UDPEchoClient {


public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Syntax: QuoteClient
<hostname> <port>");
return;
}
String hostname = args[0];
int port = Integer.parseInt(args[1]);
try {
InetAddress address =
InetAddress.getByName(hostname);
DatagramSocket socket = new DatagramSocket();
while (true)
{
DatagramPacket request = new
DatagramPacket(new byte[1], 1, address, port);
socket.send(request);
byte[] buffer = new byte[512];
DatagramPacket response = new
DatagramPacket(buffer, buffer.length);
socket.receive(response);
String quote = new String(buffer, 0,
response.getLength());
System.out.println(quote);
System.out.println();
Thread.sleep(10000);
} } catch (SocketTimeoutException
ex) {
System.out.println("Timeout error: " +
ex.getMessage()); ex.printStackTrace();
} catch (IOException ex) {
System.out.println("Client error: " +
ex.getMessage());
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}}}
• And run the client program (on the same computer):
java UDPClient localhost 17
• For the preceding application to work, UDP must be
installed and working on the host machine.

• As for TCP/IP, if there is a working Internet


connection on the machine, then UDP is running.

• In order to start the application, first open two


command windows and then

• start the server running in one window and the client


in the other. (Start the server before the client!)
INTERPROCESS COMMUNICATION
• Some issues relating to datagram communication:
• Message size: The receiving process needs to
specify an array of bytes of a particular size in
which to receive a message.
• If the message is too big for the array, it is
truncated/cut short on arrival.

• Blocking: Sockets normally provide non-blocking


sends and blocking receives for datagram
communication (a non-blocking receive is an
option in some implementations).
INTERPROCESS COMMUNICATION
• Timeouts: The receive that blocks forever is
suitable for use by a server that is waiting to
receive requests from its clients.

• But in some programs, it is not appropriate that a


process that has invoked a receive operation
should wait indefinitely in situations where

• the sending process may have crashed or the


expected message may have been lost.
INTERPROCESS COMMUNICATION
• Receive from any: The receive method does not
specify an origin for messages.

• Instead, an invocation of receive gets a message


addressed to its socket from any origin.

• The receive method returns the Internet address


and local port of the sender,

• allowing the recipient to check where the


message came from.
INTERPROCESS COMMUNICATION
• TCP stream communication
• The API to the TCP protocol, provides the abstraction
of a stream of bytes to which data may be written
and from which data may be read.

• TCP stream communication characteristics


• Message sizes
• Lost messages
• Flow control
• Message destinations
INTERPROCESS COMMUNICATION
• Some issues related to stream communication:
– Matching of data items: Two communicating
processes need to agree as to the contents of the
data transmitted over a stream.
– Blocking: The data written to a stream is kept in a
queue at the destination socket.
– Threads: When a server accepts a connection, it
generally creates a new thread in which to
communicate with the new client.
INTERPROCESS COMMUNICATION
• Java API for TCP streams
• The Java interface to TCP streams is provided in the
classes ServerSocket and Socket:

• ServerSocket: This class is intended for use by a


server to create a socket at a server port for

• listening for connect requests from clients.


• Here is a complete server program .
package com.pgx.java;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServerSocket {
private ServerSocket server;
public TCPServerSocket(String ipAddress) throws Exception {
if (ipAddress != null && !ipAddress.isEmpty())
this.server = new ServerSocket(0, 1,
InetAddress.getByName(ipAddress));
else
this.server = new ServerSocket(0, 1,
InetAddress.getLocalHost());
}
private void listen() throws Exception {
Socket client = this.server.accept();
String clientAddress = client.getInetAddress().getHostAddress();
System.out.println("\r\nNew connection from " + clientAddress);
BufferedReader in = new BufferedReader(
new InputStreamReader(client.getInputStream()));
while ( (data = in.readLine()) != null ) {
System.out.println("\r\nMessage from " + clientAddress + ": "
+ data);
}
}
public InetAddress getSocketAddress() {
return this.server.getInetAddress();
}
public int getPort() {
return this.server.getLocalPort();
}
public static void main(String[] args) throws Exception {
TCPServerSocket app = new
TCPServerSocket(args[0]);
System.out.println("\r\nRunning Server: " +
"Host=" +
app.getSocketAddress().getHostAddress() +
" Port=" + app.getPort());
app.listen();
}
}
• To run your TCPServer class:
• java -cp TCPSocketTest.jar com.pgx.java.TCPServerSocket
YourIP 53257
• Here is the client program.
package com.pgx.java;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class TCPClientSocket {
private Socket socket;
private Scanner scanner;
private TCPClientSocket(InetAddress serverAddress, int
serverPort) throws Exception {
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
private void start() throws IOException {
String input;
input = scanner.nextLine();
PrintWriter out = new
PrintWriter(this.socket.getOutputStream(), true);
out.println(input);
out.flush();
}
}
public static void main(String[] args) throws
Exception {
TCPClientSocket client = new TCPClientSocket(
InetAddress.getByName(args[0]),
Integer.parseInt(args[1]));
System.out.println("\r\nConnected to Server: " +
client.socket.getInetAddress());
client.start();
}
• Start the Client Socket Application
• To run the client socket from a terminal or Windows
command prompt, use the java command:
• Run the TCPServer first!

• java -cp TCPSocketTest.jar


com.pgx.java.TCPClientSocket Your IP ServerPort
INTERPROCESS COMMUNICATION
• External data representation and marshalling
• The information stored in running programs is
represented as data structures –

• for example, by sets of interconnected objects –


whereas the information in messages consists of
sequences of bytes.

• Irrespective of the form of communication used, the


data structures must be flattened (converted to a
sequence of bytes) before transmission and rebuilt
on arrival.
INTERPROCESS COMMUNICATION
• One of the following methods can be used to enable
any two computers to exchange binary data values:

– The values are converted to an agreed external


format before transmission and converted to the
local form on receipt;

– The values are transmitted in the sender’s format,


together with an indication of the format used,
and the recipient converts the values if necessary.
INTERPROCESS COMMUNICATION
• Marshalling is the process of taking a collection of
data items and assembling them into a form suitable
for transmission in a message.

• Unmarshalling is the process of disassembling them


on arrival to produce an equivalent collection of data
items at the destination.

• An agreed standard for the representation of data


structures and primitive values is called an external
data representation.
INTERPROCESS COMMUNICATION
• Three approaches to external data representation and
marshalling are:
• CORBA’s common data representation; which is
concerned with an external representation for the
structured and primitive types that can be passed

• as the arguments and results of remote method


invocations in CORBA.

• It can be used by a variety of programming


languages.
INTERPROCESS COMMUNICATION
INTERPROCESS COMMUNICATION
• Java’s object serialization; which is concerned
with the flattening and external data representation

• of any single object or tree of objects that may


need to be transmitted in a message or stored on a
disk.

• It is for use only by Java.


INTERPROCESS
COMMUNICATION
INTERPROCESS COMMUNICATION
• XML (Extensible Markup Language); which
defines a textual format for representing structured
data.
• It was originally intended for documents
containing textual self-describing structured data

• for example documents accessible on the Web –
but it is now also used to represent the

• data sent in messages exchanged by clients and


servers in web services.
INTERPROCESS COMMUNICATION
Quiz 3
1. Explain the usage of UDP and TCP in interprocess
communication.
2. Discuss the characteristics of interprocess communication.
3. Both forms of communication (UDP and TCP) use the
socket abstraction, explain the concept of sockets in
interprocess communication.
4. Discuss UDP datagram & TCP stream communication.
5. Discuss external data representation and marshalling
during interprocess communication process.
6. Discuss three approaches to external data representation
and marshalling.
7. What is CORBA and its application in interproces
communication?

You might also like