You are on page 1of 43

The Socket API

Mei-Ling Liu

09/30/22 Distributed Computing, M. L. Liu 1


Introduction
• The socket API is an Interprocessing
Communication (IPC) programming interface
originally provided as part of the Berkeley UNIX
operating system.
• It has been ported to all modern operating
systems, including Sun Solaris and Windows
systems.
• It is a de facto standard for programming IPC,
and is the basis of more sophisticated IPC
interface such as remote procedure call and
remote method invocation.
09/30/22 Distributed Computing, M. L. Liu 2
The conceptual model of the socket API
P ro c es s A P ro c es s B

a s o c k et

09/30/22 Distributed Computing, M. L. Liu 3


The socket API
• A socket API provides a programming
construct termed a socket. A process
wishing to communicate with another
process must create an instance, or
instantiate, such a construct
• The two processes then issues operations
provided by the API to send and receive
data.

09/30/22 Distributed Computing, M. L. Liu 4


Connection-oriented & connectionless
datagram socket
• A socket programming construct can make
use of either the UDP or TCP protocol.
• Sockets that use UDP for transport are
known as datagram sockets, while sockets
that use TCP are termed stream sockets.
• Because of its relative simplicity, we will first
look at datagram sockets, returning to
stream sockets after we have introduced the
client-server model in Chapter 5.

09/30/22 Distributed Computing, M. L. Liu 5


Connection-oriented & connectionless
datagram socket
Datagram sockets can support both connectionless
and connection-oriented communication at the
application layer. This is so because even though
datagrams are sent or received without the notion
of connections at the transport layer, the runtime
support of the socket API can create and maintain
logical connections for datagrams exchanged
between two processes, as you will see in the next
section.
(The runtime support of an API is a set of software
that is bound to the program during execution in
support of the API.)

09/30/22 Distributed Computing, M. L. Liu 6


Connection-oriented & connectionless
datagram socket
s ock e t s ock e t
A P I r unt ime Proce s s A Proce s s B A P I r untime
suppor t suppo r t

tran s port laye r s oftware tra n s po rt la ye r s oftwa re

co n n e ctio n le s s datagra m s ock e t


a d atag ram
a log ic al c on nec tion c reated an d m aintain ed
by the run tim e s u p po rt of the datag ram
s o c k et AP I

s o ck e t s o ck e t
A P I r untime Pro ce s s A Proce s s B A P I r untime
suppo r t suppo r t

tra n s po rt laye r s oftwa re tra n s po rt laye r s oftwa re

co n n e ctio n -orie n te d data gram s ock e t

09/30/22 Distributed Computing, M. L. Liu 7


The Java Datagram Socket API
In Java, two classes are provided for the
datagram socket API:
1. the DatagramSocket class for the sockets.
2. the DatagramPacket class for the datagram
exchanged.
A process wishing to send or receive
data using this API must instantiate a
DatagramSocket object, or a socket in
short. Each socket is said to be bound
to a UDP port of the machine local to
the process

09/30/22 Distributed Computing, M. L. Liu 8


The Java Datagram Socket API
To send a datagram to another process, a process:
• creates an object that represents the datagram itself.
This object can be created by instantiating a
DatagramPacket object which carries
1. (i) the payload data as a reference to a byte array,
and
2. (ii) the destination address (the host ID and port
number to which the receiver’s socket is bound.
• issues a call to a send method in the
DatagramSocket object, specifying a reference
to the DatagramPacket object as an argument

09/30/22 Distributed Computing, M. L. Liu 9


The Java Datagram Socket API
• In the receiving process, a DatagramSocket
object must also be instantiated and bound to
a local port, the port number must agree with
that specified in the datagram packet of the
sender.
• To receive datagrams sent to the socket, the
process creates a datagramPacket object
which references a byte array and calls a
receive method in its DatagramSocket object,
specifying as argument a reference to the
DatagramPacket object.
09/30/22 Distributed Computing, M. L. Liu 10
The Data Structures in the sender and
receiver programs
s e nde r pro c e s s re c e ive r pro c e s s
a by t e a rra y a by t e a rra y

r e c e i ve r 's
a dd r e s s

a D a ta g ra m Pa ck e t obje ct
a D a t a gra m Pa ck e t o bje ct

se nd
re ce iv e
a D a t a g ra m S o ck e t a D a ta g ra m S o ck e t
o bje ct o bje ct

o bje ct re f e re n ce
da t a flo w

09/30/22 Distributed Computing, M. L. Liu 11


The program flow in the sender and
receiver programs

s e nde r pr o g r am r e c e i ve r pr o g r am
create a datagram socket and
bind it to any local port; create a datagram socket and
place data in a byte array; bind it to a specific local port;
create a datagram packet, specifying create a byte array for receiving the data;
the data array and the receiver's create a datagram packet, specifying
address; the data array;
invoke the send m ethod of the invoke the receive m ethod of the
socket with a reference to the socket with a reference to the
datagram packet; datagram packet;

09/30/22 Distributed Computing, M. L. Liu 12


Event synchronization with the connectionlss
datagram socketsAPI
se r ve r c l i e nt

r e c e i ve
bl o c ki ng r e c e i ve ,
no nbl o c ki ng s e nd
requ es t i n a r e que s t-r e s po nse
se nd
pr o to c o l
r e c e i ve

bloc k ed
respo ns e
se nd

if da ta is s e n t be fo re a co rre s po n din g
re ce iv e o pe ra t io n is is s u e d, th e da ta will
be dis ca rde d by th e ru n tim e s u ppo rt
a n d will n o t be re ce iv e d.

09/30/22 Distributed Computing, M. L. Liu 13


Setting timeout
To avoid indefinite blocking, a timeout can
be set with a socket object:
void setSoTimeout(int timeout)

Set a timeout for the blocking receive from this socket, in


milliseconds.

Once set, the timeout will be in


effect for all blocking operations.

09/30/22 Distributed Computing, M. L. Liu 14


Key Methods and Constructors
Method/Constructor Description
DatagramPacket (byte[ ] buf, Construct a datagram packet for receiving packets of
int length) length length; data received will be stored in the byte
array reference by buf.
DatagramPacket (byte[ ] buf, Construct a datagram packet for sending packets of
int length, InetAddress address, length length to the socket bound to the specified port
int port) number on the specified host ; data received will be
stored in the byte array reference by buf .
DatagramSocket ( ) Construct a datagram socket and binds it to any
available port on the local host machine; this
constructor can be used for a process that sends data
and does not need to receive data.
DatagramSocket (int port) Construct a datagram socket and binds it to the
specified port on the local host machine; the port
number can then be specified in a datagram packet
sent by a sender.
void close( ) Close this datagramSocket object
void receive (DatagramPacket p) Receive a datagram packet using this socket.

void send ( DatagramPacket p) Send a datagram packet using this socket.


void setSoTimeout (int timeout) Set a timeout for the blocking receive from this
socket, in milliseconds.

09/30/22 Distributed Computing, M. L. Liu 15


The coding

// Excerpt from the sending process


//Excerpt from a receiver program InetA ddress receiverHost=
DatagramSocket ds = new DatagramSocket(2345); InetA ddress.getByName("localHost");
DatagramPacket dp = DatagramS ocket theS ocket = new DatagramSocket( );
new DatagramPacket(buffer, M A X LEN); S tring message = "Hello world!";
ds.receive(dp); byte[ ] data = message.getBytes( );
len = dp.getLength( ); data = theLine.getBytes( );
System.out.Println(len + " bytes received.\n"); DatagramPacket thePacket
String s = new S tring(dp.getData( ), 0, len); = new DatagramPacket(data, data.length,
System.out.println(dp.getA ddress( ) + " at port " receiverHost, 2345);
+ dp.getPort( ) + " says " + s); theSocket.send(theOutput);

09/30/22 Distributed Computing, M. L. Liu 16


Connectionless sockets
With connectionless sockets, it is possible for multiple
processes to simultaneously send datagrams to the same
socket established by a receiving process, in which case
the order of the arrival of these messages will be
unpredictable, in accordance with the UDP protocol
P r o ce s s B P r o ce s s B

Pro ce s s A P r o ce s s A

P ro ce s s C P r o ce s s C

F ig u re 3 a a c o n n e c t io n le ss
F ig u re 3 b
da t a gr a m so c k e t

09/30/22 Distributed Computing, M. L. Liu 17


Code samples
• Example1Sender.java, ExampleReceiver.java
• MyDatagramSocket.java,
Example2SenderReceiver.java ,
Example2ReceiverSender.java

09/30/22 Distributed Computing, M. L. Liu 18


Connection-oriented
datagram socket API

It is uncommon to employ datagram


sockets for connection-oriented
communication; the connection provided
by this API is rudimentary and typically
insufficient for applications that require a
true connection. Stream-mode sockets,
which will be introduced later, are more
typical and more appropriate for
connection-oriented communication.

09/30/22 Distributed Computing, M. L. Liu 19


Methods calls for connection-oriented datagram
socket
Method/Constructor Description
public void Create a logical connection between this socket and
connect(InetAddress address, a socket at the rem ote address and port.
int port)

public void disconnect( ) Cancel the current connection, if any, from this
socket.

A connection is made for a socket with a remote socket.


Once a socket is connected, it can only exchange data
with the remote socket.
If a datagram specifying another address is sent using
the socket, an IllegalArgumentException will occur.
If a datagram from another socket is sent to this socket,
The data will be ignored.
09/30/22 Distributed Computing, M. L. Liu 20
Connection-oriented Datagram Socket

The connection is unilateral, that is,


it is enforced only on one side. The
socket on the other side is free to
send and receive data to and from
other sockets, unless it too commits
to a connection to the other socket.
See Example3Sender,
Example3Receiver.

09/30/22 Distributed Computing, M. L. Liu 21


The Stream-mode Socket API
• The datagram socket API supports
the exchange of discrete units of data
(that is, datagrams).
• the stream socket API provides a
model of data transfer based on the
stream-mode I/O of the Unix operating
systems.
• By definition, a stream-mode socket
supports connection-oriented
communication only.
09/30/22 Distributed Computing, M. L. Liu 22
Stream-mode Socket API
(connection-oriented socket API)

a s tream -m o d e d ata s o c k et

p ro c es s
P1
P2
w r ite o p eratio n
read o p er atio n

... ...
a data str e am

09/30/22 Distributed Computing, M. L. Liu 23


Stream-mode Socket API

• A stream-mode socket is established for


data exchange between two specific
processes.
• Data stream is written to the socket at one
end, and read from the other end.
• A stream socket cannot be used to
communicate with more than one process.

09/30/22 Distributed Computing, M. L. Liu 24


Stream-mode Socket API

In Java, the stream-mode socket API is


provided with two classes:
– Server socket: for accepting connections; we
will call an object of this class a connection
socket.
– Socket: for data exchange; we will call an
object of this class a data socket.

09/30/22 Distributed Computing, M. L. Liu 25


Stream-mode Socket API program flow

c o nne c tio n lis te ne r (s e rve r) c o nne c tio n re que s te r (s e rve r)


cre a te a co n n e ctio n s o ck e t
cre a te a da ta s o ck e t
a n d lis t e n fo r co n n e ctio n
a n d re qu e s t fo r a co n n e ction ;
re qu e s ts ;
a cce pt a co n n e ctio n ;
g e t a n o u t pu t s tre a m fo r writin g
cre a te s a da ta s o ck e t fo r re a din g fro m
to th e s o ck e t;
o r writin g to th e s o ck e t s tre a m ;
write to th e s tre a m ;
g e t a n in pu t s tre a m fo r re a din g
to th e s o ck e t ;
g e t a n in pu t s tre a m fo r re adin g
re a d fro m th e s tre a m ;
to th e s o ck e t;
g e t a n o u t pu t s tre a m fo r writin g
re a d fro m th e s tre a m ;
to th e s o ck e t ;
clo s e th e da ta s ock e t.
write to th e s tre a m ;
clo s e th e da ta s o ck e t;
clo s e th e co n n e ction s o ck e t.

09/30/22 Distributed Computing, M. L. Liu 26


The server (the connection listener)

A s e rv e r u s e s t wo s o ck e ts : on e fo r a cce ptin g co n n e ctio n s , a n o th e r fo r s e n d/re ce iv e

clie n t 1

s e rv e r

co n n e c ti o n
s o ck e t

c o n n ec tio n o p er atio n
d a t a s o ck e t
clie n t 2 s en d /rec eiv e o p er ato n

09/30/22 Distributed Computing, M. L. Liu 27


Key methods in the ServerSocket class
Method/constructor Description
ServerSocket(int port) Creates a server socket on a specified port.
Socket accept() Listens for a connection to be made to this socket and
throws accepts it. The method blocks until a connection is made.
IOException
public void close() Closes this socket.
throws IOException

void Set a timeout period (in milliseconds) so that a call to


setSoTimeout(int timeout) accept( ) for this socket will block for only this amount of
throws time. If the timeout expires, a
SocketException java.io.InterruptedIOException is raised

Note: Accept is a blocking operation.

09/30/22 Distributed Computing, M. L. Liu 28


Key methods in the Socket class
Method/constructor Description
Socket(InetAddress address, Creates a stream socket and connects it to the
int port) specified port number at the specified IP address
void close() Closes this socket.
throws IOException
InputStream getInputStream( ) Returns an input stream so that data may be read
throws IOException from this socket.

OutputStream getOutputStream( Returns an output stream so that data may be written


)throws IOException to this socket.

void setSoTimeout(int timeout) Set a timeout period for blocking so that a read( )
throws SocketException call on the InputStream associated with this Socket
will block for only this amount of time. If the
timeout expires, a java.io.InterruptedIOException
is raised

A read operation on the InputStream is blocking.


A write operation is nonblocking.
09/30/22 Distributed Computing, M. L. Liu 29
Connection-oriented socket API-3
server cl i ent
1 . Serve r e stablishe s a
so cke t sd1 with lo cal sd1 Client establishes
address, then liste ns a so cket with
fo r inco m ing re m o te (se rve r's)
co nnectio n o n sd1 addre ss.

2 . Se rve r ac c epts the


c o nnec tio n request sd1
and cre ates a ne w
so c ket sd2 as a re sult.
sd2

09/30/22 Distributed Computing, M. L. Liu 30


Connection-oriented socket API-3
3 . S e r ve r is s ue s re c e ive
o pe r atio n us ing s d2 . C lie nt is s ue s
s d1
s e nd o pe r atio n.
s d2

4 . S e r ve r s e nds r e s po ns e
us ing s d2 . s d1

s d2

5 . W he n the pro to c o l
has c o m ple te d, s e rve r s d1 C lie nt c lo s e s its
c lo s e s s d2 ; s d1 is s o c ke t whe n the
us e d to ac c e pt the pr o to c o l has
ne xt c o nne c tio n c o m ple te d

09/30/22 Distributed Computing, M. L. Liu 31


Connectionless socket API
P1 P2

P1 e s ta blis h e s P2 e s tablis h e s
a loca l s ock e t a loca l s o ck e t

P1 is s u e s a P2 s e n ds a da ta gram
re ce ive o pe ration addre s s e d to P1
to re ce iv e th e
da tag ram .

09/30/22 Distributed Computing, M. L. Liu 32


Example 4 Event Diagram
ti m e
C o n n e ctio n A cce pto r C o n n e ctio n R e qu e s to r

a cce pt co n n e ct re qu e s t
(f r o m S o c k e t c o n s t r u c t o r )

re a d
w ri te
m e ssage
a n o p e r a ti o n
cl o s e
da ta s o ck e t
pro ce s s e x e cu ti n g

cl o s e
co n n e cti o n s o ck e t

cl o s e s o ck e t pro ce s s s u s pe n de d

09/30/22 Distributed Computing, M. L. Liu 33


Example4
E xam pl e 4 C o nne c ti o nAc c e pto r E xam pl e 4 C o nne c ti o nR e c e i ve r
try {
n t p o r tN o ;
S tr i n g m e s s a g e ; tr y {
// i n s ta n t i a t e s a s o c k e t fo r a cce pt i n g co n n e ct i o n In e tA d d r e s s a c c e p to r H o s t =
S e r ve r S o c k e t c o n n e c ti o n S o c k e t = n e w S e r ve r S o c k e t (p o r tN o ); In e t A d d r e s s .g e t B y N a m e ( a r g s [0 ]);
S o c k e t d a t a S o c k e t = c o n n e c ti o n S o c k e t .a c c e p t () ; i n t a c c e p t o r P o r t = In t e g e r .p a r s e In t (a r g s [1 ] );
// i n s t a n ti a t e s a d a t a s o c k e t
// g e t a o u tp u t s tr e a m f o r w r i t i n g t o t h e d a t a s o c k e t S o c k e t m y S o c k e t = n e w S o c k e t( a c c e p t o r H o s t , a c c e p t o r P o r t );
O u tp u t S tr e a m o u t S tr e a m = d a t a S o c k e t.g e t O u t p u tS t r e a m () ; // g e t a n i n p u t s tr e a m fo r r e a d i n g f r o m t h e d a ta s o c k e t
// c r e a te a P r i n te r W r i te r o b je c t fo r c h a r a c te r -m o d e o u t p u t In p u t S tr e a m i n S t r e a m = m y S o c k e t .g e tIn p u t S t r e a m ();
P r i n tW r i te r s o c k e tO u t p u t = // c r e a te a B u ff e r e d R e a d e r o b j e c t f o r t e x t- l i n e i n p u t
n e w P r i n t W r i te r (n e w O u tp u t S tr e a m W r i te r ( o u t S tr e a m )) ; B u f fe r e d R e a d e r s o c k e tIn p u t =
// w r i t e a m e s s a g e i n t o t h e d a t a s tr e a m n e w B u ff e r e d R e a d e r (n e w In p u t S tr e a m R e a d e r (i n S t r e a m ));
s o c k e tO u t p u t.p r i n tl n (m e s s a g e ); // r e a d a l i n e fr o m th e d a ta s t r e a m
//Th e e n s u i n g fl u s h m e t h o d c a l l i s n e c e s s a r y f o r th e d a t a to S t r i n g m e s s a g e = s o c k e tIn p u t .r e a d L i n e ( );
// b e w r i t te n to t h e s o c k e t d a t a s tr e a m b e f o r e th e S y s t e m .o u t .p r i n t l n (" \t " + m e s s a g e ) ;
// s o c k e t i s c l o s e d . m y S o c k e t .c l o s e ( );
s o c k e tO u t p u t.fl u s h () ; } // e n d tr y
d a t a S o c k e t.c l o s e ( ); c a tc h (Ex c e p t i o n e x ) {
c o n n e c t i o n S o c k e t.c l o s e ( ); S y s t e m .o u t .p r i n tl n (e x );
} // e n d t r y }
c a tc h ( Ex c e p ti o n e x ) {
S y s t e m .o u t.p r i n tl n (e x ) ;
}

09/30/22 Distributed Computing, M. L. Liu 34


Secure Sockets
http://java.sun.com/products/jsse/
• Secure sockets perform encryption on the data
transmitted.
• The JavaTM Secure Socket Extension (JSSE) is a Java
package that enables secure Internet communications.
• It implements a Java version of SSL (Secure Sockets
Layer) and TLS (Transport Layer Security) protocols
• It includes functionalities for data encryption, server
authentication, message integrity, and optional client
authentication.
• Using JSSE, developers can provide for the secure
passage of data between a client and a server running
any application protocol.

09/30/22 Distributed Computing, M. L. Liu 35


The Java Secure Socket Extension API
http://java.sun.com/products/jsse/doc/apidoc/index.html

• Import javax.net.ssl;
• Class SSLServerSocket is a subclass of ServerSocket,
and inherits all its methods.
• Class SSLSocket is a subclass of Socket, and inherits
all its methods.
• There are also classes for
– Certification
– Handshaking
– KeyManager
– SSLsession

09/30/22 Distributed Computing, M. L. Liu 36


Summary
• In this chapter, we introduced the socket
application program interface for
interprocess communication.
• The socket API is widely available as a
programming facility for IPC at a
relatively low level of abstraction.

09/30/22 Distributed Computing, M. L. Liu 37


Summary - 2
• Using the Java socket APIs, we
introduced two types of sockets:
– The datagram sockets, which uses the User
Datagram Protocol (UDP) at the transport
layer to provide the sending and receiving of
discrete data packets known as datagrams.
– The stream-mode socket, which uses the
Tranport Layer Protocol (TCP) at the transport
layer to provide the sending and receiving of
data using a data stream.

09/30/22 Distributed Computing, M. L. Liu 38


Summary - 3
Key points of the Java datagram socket
API:
• It supports both connectionless
communication and connection-
oriented communication.
• Each process must create a
DatagramSocket object to send/receive
datagrams.
• Each datagram is encapsulated in a
DatagramPacket object.
09/30/22 Distributed Computing, M. L. Liu 39
Summary - 4
Key points of the Java datagram socket API continued:
• In connectionless communication, a datagram
socket can be used to send to or receive from any
other datagram socket; in connection-oriented
communication, a datagram socket can only be
used to send to or receive from the datagram
socket attached to the other end of the connection.
• Data for a datagram are placed in a byte array; if a
byte array of insufficient length is provided by a
receiver, the data received will be truncated.
• The receive operation is blocking; the send
operation is non-blocking.

09/30/22 Distributed Computing, M. L. Liu 40


Summary - 5
Key points of the Java stream-mode socket API:
• It supports connection-oriented communication
only.
• A process plays the role of connection-acceptor, and
creates a connection socket using the ServerSocket
class. It then accepts connection requests from
other processes.
• A process (a connection-requestor) creates a data
socket using the Socket class, the constructor of
which issues a connection request to the connection-
acceptor.

09/30/22 Distributed Computing, M. L. Liu 41


Summary - 6
More key points of the Java stream-mode socket API :
• When a connection request is granted, the connection-
acceptor creates a data socket, of the Socket class, to send
and receive data to/from the connection-requestor. The
connection-requestor can also send and/or receive data
to/from the connection-acceptor using its data socket.
• The receive (read), the connection-accept operation, and
the connection-request operations are blocking; the send
(write) operation is non-blocking.
• The reading and writing of data into the socket of data
stream are decoupled: they can be performed in different
data units. See Figure 8.

09/30/22 Distributed Computing, M. L. Liu 42


Summary - 7
Key points of secure sockets:
• Secure socket APIs are available for
transmission of confidential data.
• Well known secure socket APIs include
the Secure Socket Layer (SSL) and Java’s
Secure Socket Extension (JSSE). Secure
socket APIs have methods that are similar
to the connection-oriented socket APIs.

09/30/22 Distributed Computing, M. L. Liu 43

You might also like