You are on page 1of 44

InterProcess

Communication

by Kumudha Raimond
Introduction
 Sockets are commonly used for client and server interaction.
 Typical system configuration places the server on one machine, with the clients on
other machines. The clients connect to the server, exchange information, and then
disconnect.
 A socket has a typical flow of events. In a connection-oriented client-to-server
model, the socket on the server process waits for requests from a client. To do
this, the server first establishes (binds) an address that clients can use to find the
server. When the address is established, the server waits for clients to request a
service.
 The client-to-server data exchange takes place when a client connects to the
server through a socket. The server performs the client's request and sends the
reply back to the client.

by Kumudha Raimond
by Kumudha Raimond
by Kumudha Raimond
TCP Sockets
Server Side
• Create a ServerSocket object
• Put the server into a waiting state
• Set up input and output streams
• Send and receive data
• Close the connection (after completion of the
dialogue)

Client Side
• Establish a connection to the server
• Set up input and output streams
• Send and receive data
• Close the connection

by Kumudha Raimond
Typical flow of events for a connection-oriented
socket:

by Kumudha Raimond
by Kumudha Raimond
Socket Class

Server Socket Class

by Kumudha Raimond
Java API for TCP
 Data stream abstraction
◦ enables reliable transfer (send can be blocking)
◦ marshaling/unmarshaling of data
◦ access to TCP parameters:
ReceiveBufferSize, SendBufferSize
 Classes Socket and ServerSocket
◦ Socket asks for connection
◦ ServerSocket listens and returns Socket
when contacted
 Port numbers
◦ explicit for ServerSocket, transparent for Socket

by Kumudha Raimond
Java API for TCP

Class ServerSocket:

 bind to a SocketAddress if unbound

 accept: listen and return a Socket


when a connection request arrives (blocking)

 close

by Kumudha Raimond
Java API for TCP
Class Socket:
 connect to SocketAddress
 getRemoteSocketAddress since that was chosen by the TCP system on
the other side
 getInputStream, getOutputStream
 use them for reading and writing
 which is/may be blocking
 DataInputStream, DataOutputStream:
 wrapper classes for streams
 have methods for marshaling/ unmarshaling
 isConnected
 close

by Kumudha Raimond
TCP Sockets
Setting up a server process requires five steps

1. Create a ServerSocket object


 The ServerSocket constructor requires a port number (1024-65535, for non-
reserved ones) as an argument.
 For example:
ServerSocket servSock = new ServerSocket(1234);
 For our example, the server will await ('listen for') a connection from a client
on port 1234.
2. Put the server into a waiting state
 The server waits indefinitely ('blocks') for a client to connect.
 It does this by calling method accept of class ServerSocket, which returns a
Socket object when a connection is made.
 For example:
Socket link = servSock.accept();

by Kumudha Raimond
TCP Sockets
Setting up a server process requires five steps

3. Set up input and output streams


 Methods getInputStream and getOutputStream of class Socket are used to get
references to streams associated with the socket returned in step 2.
 These streams will be used for communication with the client that has just made
connection.
 For a non-GUI application, we can wrap a Scanner object around the InputStream
object returned by method getInputStream, in order to obtain string-orientated input
(just as we would do with input from the standard input stream, System.in).
 For example: Scanner input = new Scanner(link.getInputStream());
 Similarly, we can wrap a PrintWriter object around the OutputStream object returned
by method getOutputStream.
 Supplying the PrintWriter constructor with a second argument of true will cause the
output buffer to be flushed for every call of println (which is usually desirable).
 For example:
PrintWriter output = new PrintWriter(link.getOutputStream(),true);
by Kumudha Raimond
TCP Sockets
Setting up a server process requires five steps

4. Send and receive data


 Having set up our Scanner and PrintWriter objects, we simply use
method nextLine for receiving data and method println for sending
data, just as we might do for console I/O.
 For example:
output.println("Awaiting data...");
String input = input.nextLine();
5. Close the connection (after completion of the dialogue)
 This is achieved via method close of class Socket.
 For example:
link.close();

by Kumudha Raimond
TCP Sockets
Setting up a client process requires FOUR steps

1. Establish a connection to the server


 We create a Socket object, supplying its constructor with the following
two arguments:
 the server's IP address (of type InetAddress);
 the appropriate port number for the service.
 We shall place client and server on the same host, which will allow us
to retrieve the IP address by calling static method getLocalHost of class
InetAddress.
 For example:
Socket link = new Socket(InetAddress.getLocalHost(),1234);

2. Set up input and output streams


 These are set up in exactly the same way as the server streams were
set up (by calling methods getInputStream and getOutputStream of
the Socket object that was created in step 2).

by Kumudha Raimond
TCP Sockets
Setting up a client process requires FOUR steps

3. Send and receive data


 The Scanner object at the client end will receive messages sent by
the PrintWriter object at the server end, while the PrintWriter
object at the client end will send messages that are received by
the Scanner object at the server end
◦ Using methods nextLine and println
4. Close the connection
 This is exactly the same as for the server process (using method
close of class Socket)

by Kumudha Raimond
Server

by Kumudha Raimond
by Kumudha Raimond
UDP Datagram Communication
Single Datagram Message : Message
User Datagram Protocol (UDP) sent in a single packet (called datagram)

• UDP is a communication protocol for time-sensitive applications like gaming,


playing videos, or Domain Name System (DNS) lookups.
• A datagram sent by UDP is transmitted from a sending process to a receiving
process without acknowledgement or retries.
• If a failure occurs, the message may not arrive.
• A datagram is transmitted between processes when one process sends it and
another receives it.

by Kumudha Raimond
UDP Datagram Communication
• Unlike TCP/IP sockets, datagram sockets are connectionless.
• That is, 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.
• 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 in TCP/IP example.
• 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
by Kumudha Raimond
UDP Datagram Single Datagram Message : Message

Communication
sent in a single packet (called datagram)

User Datagram Protocol (UDP)

• 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.
• A server will create – inform clients
• A client binds its socket to any free local port.
• The receive method returns the Internet address and port of the sender, in
addition to the message, allowing the recipient to send a reply

by Kumudha Raimond
UDP Datagram Communication
Issues relating to datagram communication:
Message size:
◦ Receiving process - specify an array of a particular size to receive a
message.
◦ If the message is too big for the array, it is truncated on arrival.
◦ The underlying IP protocol allows packet lengths of up to 216 bytes, which
includes the headers as well as the message.
◦ However, most environments impose a size restriction of 8 kilobytes.
◦ Any application requiring messages larger than the maximum must fragment
them into chunks of that size

by Kumudha Raimond
UDP Datagram Communication
Issues relating to datagram communication:
Blocking:
◦ Sockets normally provide non-blocking sends and blocking receives for
datagram communication.
◦ The send operation returns when it has handed the message to the underlying
UDP and IP protocols, which are responsible for transmitting it to its destination.
◦ On arrival, the message is placed in a queue for the socket that is bound to the
destination port.
◦ Messages are discarded at the destination if no process already has a socket
bound to the destination port

by Kumudha Raimond
UDP Datagram Communication
Issues relating to datagram communication:
Timeouts:
 The receive that blocks forever is suitable for use by a server that is waiting to
receive requests from its clients.
 But 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.
 Timeouts can be set on sockets.
 Choosing an appropriate timeout interval is difficult, but it should be fairly large
in comparison with the time required to transmit a message.

by Kumudha Raimond
UDP Datagram Communication
Issues relating to datagram 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. It is possible to connect a
datagram socket to a particular remote port and Internet address, in which case
the socket is only able to send messages to and receive messages from that
address

by Kumudha Raimond
UDP Datagram Communication
Issues relating to datagram communication:
Failure Models

UDP datagrams suffers from omission failure and ordering failure

Omission failure : Messages may be dropped occasionally, either because of a


checksum error or because no buffer space is available at the source or
destination

Ordering: Messages can sometimes be delivered out of sender order

by Kumudha Raimond
UDP Datagram Communication
Issues relating to datagram communication:
◦ Datagram service (connectionless)
◦ Data may be lost
◦ Data may arrive out of sequence
◦ Checksum for data but no retransmission
◦ Bad packets dropped

by Kumudha Raimond
Use of UDP
 Domain Name System, which looks up DNS names in the Internet, is
implemented over UDP.
 Voice over IP (VOIP) also runs over UDP.
 UDP datagrams are sometimes an attractive choice because they do not
suffer from the overheads associated with guaranteed message delivery.
 There are three main sources of overhead:
◦ the need to store state information at the source and destination;
◦ the transmission of extra messages;
◦ latency for the sender.

by Kumudha Raimond
UDP Sockets
Server Side
• 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 from the packet
• Retrieve the data from the buffer
• Create the response datagram
• Send the response datagram
• Close the Datagram Socket

by Kumudha Raimond
UDP Sockets
Client Side
• Create a DatagramSocket object
• Create the outgoing datagram
• Send the datagram message
• Create a buffer for incoming datagrams
• Create a DatagramPacket object for the incoming datagrams
• Accept an incoming datagram
• Retrieve the data from the buffer
• Close the DatagramSocket

by Kumudha Raimond
Java API for UDP Datagrams
The Java API provides datagram
communication by means of two classes:
DatagramPacket and DatagramSocket.

This class provides a constructor that makes an instance out of an array of bytes
comprising a
message, the length of the message and the Internet address and local port
number of the destination socket.
Datagram packet

An instance of DatagramPacket may be transmitted between processes when one


process sends it and another receives it.
UDP server repeatedly receives a request and sends it back to the client
by Kumudha Raimond
Java API for UDP Datagrams
Datagram packet
This class provides another constructor for use when receiving a message.

Its arguments specify an array of bytes in which to receive the message and the
length of the array.

A received message is put in the DatagramPacket together with its length and the
Internet address and port of the sending socket.

The message can be retrieved from the DatagramPacket by means of the method
getData.

The methods getPort and getAddress access the port and Internet address.
by Kumudha Raimond
Java API for UDP Datagrams

Datagram Socket

• This class supports sockets for sending and receiving UDP datagrams.
• It provides a constructor that takes a port number as its argument, for use
by processes that need to use a particular port.
• It also provides a no-argument constructor that allows the system to
choose a free local port.
• These constructors can throw a SocketException if the chosen port is
already in use or if a reserved port is specified

by Kumudha Raimond
Java API for UDP Datagrams
The class DatagramSocket rovides methods
send and receive: These methods are for transmitting datagrams between a
pair of sockets. The argument of send is an instance of DatagramPacket
containing a message and its destination. The argument of receive is an empty
DatagramPacket in which to put the message, its length and its origin. The
methods send and receive can throw IOExceptions.
setSoTimeout: This method allows a timeout to be set. With a timeout set, the
receive method will block for the time specified and then throw an
InterruptedIOException.
connect: This method is used for connecting to a particular remote port and
Internet address, in which case the socket is only able to send messages to and
receive messages from that address
by Kumudha Raimond
Java API for UDP Datagrams
Class DatagramSocket
 socket constructor
◦ bound to free port if no arg
◦ arguments InetAddress, Port
 send a DatagramPacket, non-blocking
 receive DatagramPacket, blocking
 setSoTimeout (receive blocks for time T and throw
InterruptedIOException)
 close DatagramSocket
 throws SocketException if port unknown or in use
 connect and disconnect (!!??)
 setReceiveBufferSize and setSendBufferSize

by Kumudha Raimond
UDP Sockets
Setting up a server process requires NINE steps
1. Create a DatagramSocket object
 Just as for the creation of a ServerSocket object, this means supplying the
object's constructor with the port number.
 For example:
DatagramSocket datagramSocket = new DatagramSocket(1234);
2. Create a buffer for incoming datagrams
 This is achieved by creating an array of bytes.
 For example:
byte[] buffer = new byte[256];
3. Create a DatagramPacket object for the incoming datagrams
 The constructor for this object requires two arguments:
 The previously-created byte array;
 The size of this array.
 For example:
DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);
by Kumudha Raimond
UDP Sockets
Setting up a server process requires NINE steps

4. Accept an incoming datagram


 This is effected via the receive method of our DatagramSocket
object, using our DatagramPacket object as the receptacle.
 For example:
datagramSocket.receive(inPacket);

5. Accept the sender's address and port from the packet


 Methods getAddress and getPort of DatagramPacket object are
used for this.
 For example:
InetAddress clientAddress = inPacket.getAddress();
int clientPort = inPacket.getPort();

by Kumudha Raimond
UDP Sockets
Setting up a server process requires NINE steps

6. Retrieve the data from the buffer


 For convenience of handling, the data will be retrieved as a string,
using an overloaded form of the String constructor that takes three
arguments:
 A byte array;
 The start position within the array (= 0 here);
 The number of bytes (= full size of buffer here).
 For example:
String message = new String(inPacket.getData(),0,inPacket.getLength());

by Kumudha Raimond
UDP Sockets
Setting up a server process requires NINE steps
7. Create the response datagram
 Create a DatagramPacket object, using an overloaded form of the
constructor that takes four arguments:
 The byte array containing the response message;
 The size of the response;
 The client's address;
 The client's port number.
 The first of these arguments is returned by the getBytes method of the
String class (acting on the desired String response).
 For example:
DatagramPacket outPacket = new DatagramPacket(response.getBytes(),
response.length(),clientAddress, clientPort);
 Here, response is a String variable holding the return message.

by Kumudha Raimond
UDP Sockets
Setting up a server process requires NINE steps

8. Send the response datagram


 This is achieved by calling method send of our DatagramSocket
object, supplying our outgoing DatagramPacket object as an
argument.
 For example:
datagramSocket.send(outPacket);
 Steps 4-8 may be executed indefinitely (within a loop).
 Under normal circumstances, the server would probably not be
closed down at all.
 However, if an exception occurs, then the associated
DatagramSocket should be closed, as shown in step 9 below.
9. Close the DatagramSocket
 This is effected simply by calling method close of our
DatagramSocket object. For
 example:
datagramSocket.close();
by Kumudha Raimond
UDP Sockets
Setting up a CLIENT process requires EIGHT steps

1. Create a DatagramSocket object


 This is similar to the creation of a DatagramSocket object in the
server program, but with the important difference that the
constructor here requires no argument, since a default port (at the
client end) will be used.
 For example:
DatagramSocket datagramSocket = new DatagramSocket();
2. Create the outgoing datagram
 This step is exactly as for step 7 of the server program. For
example:
DatagramPacket outPacket = new
DatagramPacket(message.getBytes(), message.length(), host,
PORT);

by Kumudha Raimond
UDP Sockets
Setting up a CLIENT process requires EIGHT steps

3. Send the datagram message


 Just as for the server, this is achieved by calling method send of the
DatagramSocket object, supplying our outgoing DatagramPacket
object as an argument.
 For example:
datagramSocket.send(outPacket);
 Steps 4-6 below are exactly the same as steps 2-4 of the server
procedure.
4. Create a buffer for incoming datagrams
 For example:
byte[] buffer = new byte[256];

by Kumudha Raimond
UDP Sockets
Setting up a CLIENT process requires EIGHT steps

5. Create a DatagramPacket object for the incoming datagrams


For example:
DatagramPacket inPacket =new DatagramPacket(buffer,
buffer.length);
6. Accept an incoming datagram
 For example:
datagramSocket.receive(inPacket);

by Kumudha Raimond
UDP Sockets
Setting up a CLIENT process requires EIGHT steps

7. Retrieve the data from the buffer


 This is the same as step 6 in the server program. For example:
String response =
new String(inPacket.getData(),0, inPacket.getLength());
 Steps 2-7 may then be repeated as many times as required.
8. Close the DatagramSocket
 This is the same as step 9 in the server program. For example:
datagramSocket.close();

by Kumudha Raimond

You might also like