The Client-Server Paradigm

advertisement
Distributed Computing Paradigms
&
Programming the JAVA socket API
René de Vries
([email protected])
Based on slides by M.L. Liu
February 14th, 2006
Integratie van Sofware Systemen
1
Distributed Computing Paradigms
René de Vries
([email protected])
Based on slides by M.L. Liu
February 14th, 2006
Integratie van Sofware Systemen
2
Paradigms for Distributed Applications
Important characteristics that distinguish distributed applications
from conventional applications which run on a single machine:
 Interprocess communication: A distributed application requires
the participation of two or more independent entities
(processes). To do so, the processes must have the ability to
exchange data among themselves.
 Event synchronization: In a distributed application,
the
sending and receiving of data among the participants of a
distributed application must be synchronized.
 Paradigm means “a pattern, example, or model.” In the study
of any subject of great complexity, it is useful to identify the
basic patterns or models, and classify the detail according to
these models. This talk aims to present a classification of the
paradigms for distributed applications.
February 14th, 2006
Integratie van Sofware Systemen
3
Abstractions
Arguably the most fundamental concept in computer science,
abstraction is the idea of detail hiding.
We often use abstraction when it is not necessary to know
the exact details of how something works or is represented,
because we can still make use of it in its simplified form.
Getting involved with the detail often tends to obscure what
we are trying to understand, rather than illuminate it.
Abstraction plays a very important role in programming
because we often want to model, in software, simplified
versions of things that exist in the real world without having
to build the real things.
In software engineering, abstraction is realized with the provision
of tools or facilities which allow software to be built without the
developer having to be cognizant of some of the underlying
complexities.
February 14th, 2006
Integratie van Sofware Systemen
4
Overview of presented Paradigms
 Message passing




Remote Procedure Call
Client-server
Peer-to-Peer
Message system:
o Point-to-point;
o Publish/Subscribe
 Distributed objects:
o Remote method invocation
o Network services
o Object Request Broker
o Object space
o Component Based Technologies
 Mobile agents
 Collaborative applications
February 14th, 2006
Integratie van Sofware Systemen
5
The Message Passing Paradigm
Message passing is the most fundamental paradigm for distributed
applications.
A process sends a message representing a request.
The message is delivered to a receiver, which processes the request,
and sends a message in response.
In turn, the reply may trigger a further request, which leads to a
subsequent reply, and so forth.
Process A
Process B
a message
Message passing
February 14th, 2006
Integratie van Sofware Systemen
6
The Message Passing Paradigm - 2
The basic operations required to support the basic message
passing paradigm are send, and receive.
For connection-oriented communication, the operations connect
and disconnect are also required.
With the abstraction provided by this model, the interconnected
processes perform input and output to each other, in a manner
similar to file I/O. The I/O operations encapsulate the detail of
network communication at the operating-system level.
The socket application programming interface is based on this
paradigm.
 http://java.sun.com/products/jdk/1.2/docs/api/index.html
 http://www.sockets.com/
February 14th, 2006
Integratie van Sofware Systemen
7
Overview of presented Paradigms
 Message passing
 Remote Procedure Call
 Client-server
 Peer-to-Peer
 Message system:
o Point-to-point;
o Publish/Subscribe
 Distributed objects:
o Remote method invocation
o Network services
o Object Request Broker
o Object space
o Component Based Technologies
 Mobile agents
 Collaborative applications
February 14th, 2006
Integratie van Sofware Systemen
8
Remote Procedure Call
As applications grew increasingly complex, it became desirable to have
a paradigm which allows distributed software to be programmed in a
manner similar to conventional applications which run on a single
processor.
The Remote Procedure Call (RPC) model provides such an
abstraction. Using this model, interprocess communications proceed as
procedure, or function, calls, which are familiar to application
programmers.
A remote procedure call involves two independent processes, which
may reside on separate machines.
 A process, A, wishing to make a request to another process, B,
issues a procedure call to B, passing with the call a list of argument
values.
 As in the case of local procedure calls, a remote procedure call
triggers a predefined action in a procedure provided by process B.
 At the completion of the procedure, process B returns a value to
process A.
February 14th, 2006
Integratie van Sofware Systemen
9
Remote Procedure Call - 2
Process B
Process A
proc1(arg1, arg2)
proc2(arg1)
proc3(arg1,arg2,arg3)
February 14th, 2006
Integratie van Sofware Systemen
10
Remote Procedure Call - 3
RPC allows programmers to build network applications using a
programming construct similar to the local procedure call,
providing a convenient abstraction for both interprocess
communication and event synchronization.
Since its introduction in the early 1980s, the Remote Procedure
Call model has been widely in use in network applications.
There are two prevalent APIs for Remote Procedure Calls.

The Open Network Computing Remote Procedure Call,
evolved from the RPC API originated from Sun
Microsystems in the early 1980s.
 The Open Group Distributed Computing Environment (DCE)
RPC.
Both APIs provide a tool, rpcgen, for transforming remote
procedure calls to local procedure calls.
February 14th, 2006
Integratie van Sofware Systemen
11
Overview of presented Paradigms
 Message passing
 Remote Procedure Call
 Client-server
 Peer-to-Peer
 Message system:
o Point-to-point;
o Publish/Subscribe
 Distributed objects:
o Remote method invocation
o Network services
o Object Request Broker
o Object space
o Component Based Technologies
 Mobile agents
 Collaborative applications
February 14th, 2006
Integratie van Sofware Systemen
12
The Client-Server Paradigm
Perhaps the best known paradigm for network applications, the
client-server model,
assigns asymmetric roles to two
collaborating processes.
One process, the server, plays the role of a service provider
which waits passively for the arrival of requests. The other, the
client, issues specific requests to the server and awaits its
response.
service request
a client process
a server process
Server host
a service
...
Client host
The Client-Server Paradigm, conceptual
February 14th, 2006
Integratie van Sofware Systemen
13
The Client-Server Paradigm - 2
Simple in concept, the client-server model provides an efficient
abstraction for the delivery of network services.
Operations required include those for a server process to listen
and to accept requests, and for a client process to issue
requests and accept responses.
By assigning asymmetric roles to the two sides, event synchronization is simplified: the server process waits for requests, and
the client in turn waits for responses.
Many Internet services are client-server applications. These
services are often known by the protocol that the application
implements. Well known Internet services include HTTP, FTP,
DNS, finger, gopher, etc.
February 14th, 2006
Integratie van Sofware Systemen
14
Overview of presented Paradigms
 Message passing
 Remote Procedure Call
 Client-server
 Peer-to-Peer
 Message system:
o Point-to-point;
o Publish/Subscribe
 Distributed objects:
o Remote method invocation
o Network services
o Object Request Broker
o Object space
o Component Based Technologies
 Mobile agents
 Collaborative applications
February 14th, 2006
Integratie van Sofware Systemen
15
The Peer-to-Peer Paradigm
In system architecture and networks, peer-to-peer is
an architecture where computer resources and
services are direct exchanged between computer
systems.
These resources and services include the exchange
of information, processing cycles, cache storage, and
disk storage for files.
In such an architecture, computers that have
traditionally been used solely as clients communicate
directly among themselves and can act as both
clients and servers, assuming whatever role is most
efficient for the network.
http://www.peer-to-peerwg.org/whatis/index.html
February 14th, 2006
Integratie van Sofware Systemen
16
The Peer-to-Peer Paradigm - 2
In the peer-to-peer paradigm, the participating processes play
equal roles, with equivalent capabilities and responsibilities
(hence the term “peer”). Each participant may issue a request
to another participant and receive a response.
process 1
re qu e st
re qu e st
re spon se
re spon se
process 2
February 14th, 2006
Integratie van Sofware Systemen
17
The Peer-to-Peer Paradigm - 3
Whereas the client-server paradigm is an ideal model
for a centralized network service, the peer-to-peer
paradigm is more appropriate for applications such
as instant messaging, peer-to-peer file transfers,
video conferencing, and collaborative work. It is also
possible for an application to be based on both the
client-server model and the peer-to-peer model.
A well-known example of a peer-to-peer file transfer
service is Napster.com or similar sites which allow
files (primarily audio files) to be transmitted among
computers on the Internet. It makes use of a server
for directory in addition to the peer-to-peer
computing.
February 14th, 2006
Integratie van Sofware Systemen
18
February 14th, 2006
Integratie van Sofware Systemen
19
The Peer-to-Peer Paradigm - 4
The peer-to-peer paradigm can be implemented with
facilities using any tool that provide message-passing, or
with a higher-level tool such as one that supports the pointto-point model of the Message System paradigm.
For web applications, the web agent is a protocol promoted
by the XNSORG (the XNS Public Trust Organization) for
peer-to-peer interprocess communication
“Project JXTA is a set of open, generalized peer-to-peer
protocols that allow any connected device (cell phone, to
PDA, PC to server) on the network to communicate and
collaborate. JXTA is short for Juxtapose, as in side by side.
It is a recognition that peer to peer is juxtapose to client
server or Web based computing -- what is considered
today's traditional computing model. “
February 14th, 2006
Integratie van Sofware Systemen
20
Overview of presented Paradigms




Message passing
Remote Procedure Call
Client-server
Peer-to-Peer
 Message system:
o Point-to-point;
o Publish/Subscribe
 Distributed objects:
o Remote method invocation
o Network services
o Object Request Broker
o Object space
o Component Based Technologies
 Mobile agents
 Collaborative applications
February 14th, 2006
Integratie van Sofware Systemen
21
The Message System Paradigm
The Message System or Message-Oriented Middleware (MOM)
paradigm is an elaboration of the basic message-passing paradigm.
In this paradigm, a message system serves as an intermediary among
separate, independent processes.
The message system acts as a switch for messages, through which
processes exchange messages asynchronously, in a decoupled
manner.
A sender deposits a message with the message system, which
forwards it to a message queue associated with each receiver. Once a
message is sent, the sender is free to move on to other tasks.
receivers
message system
sender
...
...
February 14th, 2006
Integratie van Sofware Systemen
22
The Point-To-Point Message Model
In this model, a message system forwards a message from the
sender to the receiver’s message queue.
 Unlike the basic message passing model, the middleware
provides a message depository, and allows the sending and
the receiving to be decoupled.
 Via the middleware, a sender deposits a message in the
message queue of the receiving process.
 A receiving process extracts the messages from its message
queue, and handles each one accordingly.
Compared to the basic message-passing model, this paradigm
provides the additional abstraction for asynchronous operations.
To achieve the same effect with basic message-passing, a
developer will have to make use of threads or child processes.
February 14th, 2006
Integratie van Sofware Systemen
23
The Publish/Subscribe Message Model
The publish/subscribe message model offers a powerful
abstraction for multicasting or group communication.
 The publish operation allows a process to multicast to a
group of processes,
 and the subscribe operation allows a process to listen for
such multicast.
Each message is then associated with a specific topic or event.
 Applications interested in the occurrence of a specific event
may subscribe to messages for that event.
 When the awaited event occurs, the process publishes a
message announcing the event or topic.
 The middleware message system distributes the message to
all its subscribers.
February 14th, 2006
Integratie van Sofware Systemen
24
Toolkits based on the Message-System Paradigm
The MOM paradigm has had a long history in distributed
applications.
Message Queue Services (MQS) have been in use since the
1980’s.
The IBM MQ*Series is an example of such a facility.
http://www-4.ibm.com/software/ts/mqseries/
Other existing support for this paradigm:
 Microsoft’s Message Queue (MSQ),
http://msdn.microsoft.com/library/psdk/msmq/msmq_overvie
w_4ilh.htm

Java’s Message Service
http://developer.java.sun.com/developer/technicalArticles/Ne
tworking/messaging/
February 14th, 2006
Integratie van Sofware Systemen
25
Overview of presented Paradigms





Message passing
Remote Procedure Call
Client-server
Peer-to-Peer
Message system:
o Point-to-point;
o Publish/Subscribe
 Distributed objects:
o Remote method invocation
o Network services
o Object Request Broker
o Object space
o Component Based Technologies
 Mobile agents
 Collaborative applications
February 14th, 2006
Integratie van Sofware Systemen
26
The Distributed Objects Paradigms
The idea of applying object orientation to distributed
applications is a natural extension of object-oriented
software development.
Applications access objects distributed over a
network.
Objects provide methods, through the invocation of
which an application obtains access to services.
Object-oriented paradigms include:
 Remote method invocation (RMI)
 Network services
 Object Request Broker
 Object spaces
February 14th, 2006
Integratie van Sofware Systemen
27
Remote Method Invocation (RMI)
Remote method invocation is the object-oriented equivalent of
remote method calls.
In this model, a process invokes the methods in an object,
which may reside in a remote host.
As with RPC, arguments may be passed with the invocation.
Process 2
Process 1
remote method invocation
method1
method2
a remote object
The Remote Method Call Paradigm
February 14th, 2006
Integratie van Sofware Systemen
28
The Network Services Paradigm
In this paradigm, service providers register themselves with directory
servers on a network. A process desiring a particular service contacts
the directory server at run time, and, if the service is available, will be
provided a reference to the service. Using the reference, the process
interacts with the service.
This paradigm is essentially an extension of the remote method call
paradigm. The difference is that service objects are registered with a
global directory service, allowing them to be look up and accessed by
service requestors on a federated network.
Java’s Jini technology is based on this paradigm.
Directory service
service object
Service requestor
February 14th, 2006
Integratie van Sofware Systemen
29
The Network Services Paradigm - 2
Web-services extend the network of a message network service
to the complete internet.
With web-services processes can communicate over HTTP.
Data is transferred using XML-based SOAP (Simple Object
Access Protocol).
service
object
web
server
method name,
parameter list
return value
web
client
HTTP request
HTTP response
February 14th, 2006
Integratie van Sofware Systemen
30
The Object Request Broker Paradigm
In the object broker paradigm , an application issues requests to an
object request broker (ORB), which directs the request to an
appropriate object that provides the desired service.
The paradigm closely resembles the remote method invocation model
in its support for remote object access. The difference is that the object
request broker in this paradigm functions as a middleware which allows
an application, as an object requestor, to potentially access multiple
remote (or local) objects.
The request broker may also function as an mediator for
heterogeneous objects, allowing interactions among objects
implemented using different APIs and /or running on different platforms.
Object
Requestor
Object
Object Request Broker
February 14th, 2006
Integratie van Sofware Systemen
31
The Object Request Broker Paradigm - 2
This paradigm is the basis of the Object Management Group’s
CORBA (Common Object Request Broker Architecture)
architecture.
http://www.corba.org/
Tool kits based on the architecture include:

Inprise’s Visibroker http://www.inprise.com/visibroker/

Java’s Interface Development Language (Java IDL)
http://java.sun.com/products/jdk/idl/

Orbix’s IONA, and TAO from the Object Computing, Inc.
http://www.corba.org/vendors/pages/iona.html
February 14th, 2006
Integratie van Sofware Systemen
32
The Object Space Paradigm
Perhaps the most abstract of the object-oriented paradigms, the
object space paradigm assumes the existence of logical entities
known as object spaces.
The participants of an application converge in a common object
space.
A provider places objects as entries into an object space, and
requesters who subscribe to the space access the entries.
requestor
provider
rea
d
requestor
write
read
An Object Space
February 14th, 2006
Integratie van Sofware Systemen
33
The Object Space Paradigm - 2
In addition to the abstractions provided by other
paradigms, the object space paradigm provides a
virtual space or meeting room among provides and
requesters of network resources or objects.
This abstraction hides the detail involved in resource
or object lookup needed in paradigms such as
remote method invocation, object request broker, or
network services.
Current facilities based on this paradigm include
JavaSpaces
http://java.sun.com/products/javaspaces/.
February 14th, 2006
Integratie van Sofware Systemen
34
Component-based Technologies
Component-based technologies such as Microsoft’s
COM, Microsoft DCOM, Microsoft .Net, CORBA, Java
Bean, and Enterprise Java Bean are also based on
distributed-object paradigms, as components are
essentially specialized, packaged objects designed to
interact with each other through standardized
interfaces.
In addition, application servers, popular for enterprise
applications, are middleware facilities which provide
access to objects or components.
IBM’s WebSphere,
http://www.as400.ibm.com/products/websphere/docs/
as400v35/docs/admover.html
February 14th, 2006
Integratie van Sofware Systemen
35
Overview of presented Paradigms





Message passing
Remote Procedure Call
Client-server
Peer-to-Peer
Message system:
o Point-to-point;
o Publish/Subscribe
 Distributed objects:
o Remote method invocation
o Network services
o Object Request Broker
o Object space
o Component Based Technologies
 Mobile agents
 Collaborative applications
February 14th, 2006
Integratie van Sofware Systemen
36
The Mobile Agent Paradigm
A mobile agent is a transportable program or object.
In this model, an agent is launched from an originating host.
The agent travels from host to host according to an itinerary
that it carries.
At each stop, the agent accesses the necessary resources or
services, and performs the necessary tasks to accomplish its
mission.
Host 2
Host 1
Host 3
agent
Host 4
February 14th, 2006
Integratie van Sofware Systemen
37
The Mobile Agent Paradigm - 2
The paradigm offers the abstraction for a transportable
program or object.
In lieu of message exchanges, data is carried by the
program/object as the program is transported among
the participants.
Commercial packages which support the mobile agent
paradigm include:
 Mitsubishi Electric ITA’s Concordia system
http://www.meitca.com/HSL/Projects/Concordia/Welc
ome.html
 IBM’s Aglet system.
http://www.trl.ibm.co.jp/aglets/
February 14th, 2006
Integratie van Sofware Systemen
38
Overview of presented Paradigms





Message passing
Remote Procedure Call
Client-server
Peer-to-Peer
Message system:
o Point-to-point;
o Publish/Subscribe
 Distributed objects:
o Remote method invocation
o Network services
o Object Request Broker
o Object space
o Component Based Technologies
 Mobile agents
 Collaborative applications
February 14th, 2006
Integratie van Sofware Systemen
39
The Collaborative Application (Groupware) Paradigm
In this model, processes participate in a collaborative session
as a group.
Each participating process may contribute input to part or all of
the group.
Processes may do so using:
 multicasting to send data to all or part of the group, or they
may use
 virtual sketchpads or whiteboards which allows each
participant to read and write data to a shared display.
message
message
message
Message-based groupware paradigm
February 14th, 2006
Whiteboard-based groupware paradigm
Integratie van Sofware Systemen
40
Overview of presented Paradigms





Message passing
Remote Procedure Call
Client-server
Peer-to-Peer
Message system:
o Point-to-point;
o Publish/Subscribe
 Distributed objects:
o Remote method invocation
o Network services
o Object Request Broker
o Object space
o Component Based Technologies
 Mobile agents
 Collaborative applications
February 14th, 2006
Integratie van Sofware Systemen
41
Choosing a paradigm
To varying degrees, paradigms provide abstractions
that insulate the developers from the detail of
interprocess
communication
and
event
synchronization, allowing the programmer to
concentrate on the bigger picture of the application
itself.
In choosing a paradigm or a tool for an application,
there are tradeoffs that should be considered,
including overheads, scalability, cross-platform
support, and software engineering issues.
February 14th, 2006
Integratie van Sofware Systemen
42
Programming the
JAVA Socket API
René de Vries
([email protected])
Based on slides by M.L. Liu
February 14th, 2006
Integratie van Sofware Systemen
43
Overview
Introduction
Connectionless datagram transport
Connection oriënted datagram transport
Streaming transport
Secure transport
Conclusions
References
February 14th, 2006
Integratie van Sofware Systemen
44
Introduction
The socket API is an Interprocess Communications (IPC) programming
interface;
Originally provided as part of the Berkeley UNIX operating system (1980);
It is a de facto standard for programming IPC;
Adopted by many modern operating systems, e.g. Sun Solaris and Windows
systems;
Underlying service for sophisticated IPC, e.g. RPC, RMI, CORBA, Web
Services, etc.
February 14th, 2006
Integratie van Sofware Systemen
45
The conceptual model of the socket API
Process A
Process B
a socket
February 14th, 2006
Integratie van Sofware Systemen
46
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.
February 14th, 2006
Integratie van Sofware Systemen
47
Internet Protocols
UDP
 Connectionless
 Unreliable
 No FIFO guarantee
TCP
 Connection Oriënted
 Reliable
 FIFO
February 14th, 2006
Integratie van Sofware Systemen
48
Connection-oriented & connectionless datagram
socket
Sockets can make use of either the UDP or TCP;
UDP sockets are datagram sockets;
TCP sockets are stream sockets;
February 14th, 2006
Integratie van Sofware Systemen
49
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.)
February 14th, 2006
Integratie van Sofware Systemen
50
Connection-oriented & connectionless datagram
socket
socket
API runtime
support
Process A
Process B
socket
API runtime
support
transport layer software
transport layer software
connectionless datagram socket
a datagram
a logical connection created and maintained
by the runtime support of the datagram
socket API
socket
API runtime
support
Process A
Process B
socket
API runtime
support
transport layer software
transport layer software
connection-oriented datagram socket
February 14th, 2006
Integratie van Sofware Systemen
51
Overview
Introduction
Connectionless datagram transport
Connection oriënted datagram transport
Streaming transport
Secure transport
Conclusions
References
February 14th, 2006
Integratie van Sofware Systemen
52
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
February 14th, 2006
Integratie van Sofware Systemen
53
The Java Datagram Socket API
Sending process
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.
2.
(i) the payload data as a reference to a byte array, and
(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
February 14th, 2006
Integratie van Sofware Systemen
54
The Java Datagram Socket API
Receiving process
A DatagramSocket object must be instantiated and bound to a local port;

The port number is the addresss specified in the datagram packet of the
sender.
Data is received in a created datagramPacket object (includes a byte array
reference);
Invoke a receive method in its DatagramSocket object, specifying as argument
a reference to the DatagramPacket object.
February 14th, 2006
Integratie van Sofware Systemen
55
The Data Structures in the sender and receiver programs
sender process
receiver process
a byte array
a byte array
receiver's
address
a DatagramPacket object
a DatagramPacket object
send
receive
a DatagramSocket
object
a DatagramSocket
object
object reference
data flow
February 14th, 2006
Integratie van Sofware Systemen
56
The program flow in the sender and receiver
programs
sender program
create a datagram socket and
bind it to any local port;
place data in a byte array;
create a datagram packet, specifying
the data array and the receiver's
address;
invoke the send method of the
socket with a reference to the
datagram packet;
February 14th, 2006
receiver program
create a datagram socket and
bind it to a specific local port;
create a byte array for receiving the data;
create a datagram packet, specifying
the data array;
invoke the receive method of the
socket with a reference to the
datagram packet;
Integratie van Sofware Systemen
57
Event synchronization with the connectionlss datagram socketsAPI
server
client
receive
request
send
blocking receive,
nonblocking send
in a request-response
protocol
receive
blocked
response
send
if data is sent before a corresponding
receive operation is issued, the data will
be discarded by the runtime support
and will not be received.
February 14th, 2006
Integratie van Sofware Systemen
58
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.
If the timeout expires, a java.net.SocketTimeoutException is raised
February 14th, 2006
Integratie van Sofware Systemen
59
Key Methods and Constructors
Method/Constructor
Description
DatagramPacket (byte[ ] buf,
int length)
Construct a datagram packet for receiving packets of
length length; data received will be stored in the byte
array reference by buf.
DatagramPacket (byte[ ] buf,
int length, InetAddress address,
Construct a datagram packet for sending packets of
length length to the socket bound to the specified port
number on the specified host ; data received will be
stored in the byte array reference by buf .
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.
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.
Close this datagramSocket object
Receive a datagram packet using this socket.
int port)
DatagramSocket ( )
DatagramSocket (int port)
void close( )
void receive (DatagramPacket p)
void send ( DatagramPacket p)
void setSoTimeout (int timeout)
February 14th, 2006
Send a datagram packet using this socket.
Set a timeout for the blocking receive from this
socket, in milliseconds.
Integratie van Sofware Systemen
60
The coding
//Excerpt from a receiver program
DatagramSocket ds = new DatagramSocket(2345);
DatagramPacket dp =
new DatagramPacket(buffer, MAXLEN);
ds.receive(dp);
len = dp.getLength( );
System.out.Println(len + " bytes received.\n");
String s = new String(dp.getData( ), 0, len);
System.out.println(dp.getAddress( ) + " at port "
+ dp.getPort( ) + " says " + s);
February 14th, 2006
// Excerpt from the sending process
InetAddress receiverHost=
InetAddress.getByName("localHost");
DatagramSocket theSocket = new DatagramSocket( );
String message = "Hello world!";
byte[ ] data = message.getBytes( );
data = theLine.getBytes( );
DatagramPacket thePacket
= new DatagramPacket(data, data.length,
receiverHost, 2345);
theSocket.send(theOutput);
Integratie van Sofware Systemen
61
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
Process B
Process A
Process B
Process A
Process C
Figure 3a
February 14th, 2006
a connect ionless
dat agram socket
Integratie van Sofware Systemen
Process C
Figure 3b
62
Code samples
Example1Sender.java, ExampleReceiver.java
MyDatagramSocket.java, Example2SenderReceiver.java ,
Example2ReceiverSender.java
February 14th, 2006
Integratie van Sofware Systemen
63
Overview
Introduction
Connectionless datagram transport
Connection oriënted datagram transport
Streaming transport
Secure transport
Conclusions
References
February 14th, 2006
Integratie van Sofware Systemen
64
Connection-oriented
datagram socket API
It is uncommon to employ datagram sockets for connection-oriented
communication;
A 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.
February 14th, 2006
Integratie van Sofware Systemen
65
Methods calls for connection-oriented datagram socket
Method/Constructor
public void
connect(InetAddress address,
int port)
Description
Create a logical connection between this socket and
a socket at the rem ote address and 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.
February 14th, 2006
Integratie van Sofware Systemen
66
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.
February 14th, 2006
Integratie van Sofware Systemen
67
Overview
Introduction
Connectionless datagram transport
Connection oriënted datagram transport
Streaming transport
Secure transport
Conclusions
References
February 14th, 2006
Integratie van Sofware Systemen
68
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 connectionoriented communication only.
February 14th, 2006
Integratie van Sofware Systemen
69
Stream-mode Socket API
(connection-oriented socket API)
a stream-mode data socket
process
P1
P2
write operation
read operation
...
...
a data stream
February 14th, 2006
Integratie van Sofware Systemen
70
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.
February 14th, 2006
Integratie van Sofware Systemen
71
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.
February 14th, 2006
Integratie van Sofware Systemen
72
Stream-mode Socket API program flow
connection listener (server)
create a connection socket
and listen for connection
requests;
accept a connection;
creates a data socket for reading from
or writing to the socket stream;
get an input stream for reading
to the socket;
read from the stream;
get an output stream for writing
to the socket;
write to the stream;
close the data socket;
close the connection socket.
February 14th, 2006
connection requester (server)
create a data socket
and request for a connection;
get an output stream for writing
to the socket;
write to the stream;
get an input stream for reading
to the socket;
read from the stream;
close the data socket.
Integratie van Sofware Systemen
73
The server (the connection listener)
A server uses two sockets: one for accepting connections, another for send/receive
client 1
server
connection
socket
connection operation
data socket
client 2
February 14th, 2006
Integratie van Sofware Systemen
send/receive operaton
74
Key methods in the ServerSocket class
Method/constructor
ServerSocket(int port)
Socket accept()
throws
IOException
public void close()
throws IOException
Description
Creates a server socket on a specified port.
Listens for a connection to be made to this socket and
accepts it. The method blocks until a connection is made.
void
setSoTimeout(int timeout)
throws
SocketException
Set a timeout period (in milliseconds) so that a call to
accept( ) for this socket will block for only this amount of
time. If the timeout expires, a
java.io.InterruptedIOException is raised
Closes this socket.
Note: Accept is a blocking operation.
February 14th, 2006
Integratie van Sofware Systemen
75
Key methods in the Socket class
Method/constructor
Socket(InetAddress address,
int port)
void close()
throws IOException
InputStream getInputStream( )
throws IOException
Description
Creates a stream socket and connects it to the
specified port number at the specified IP address
Closes this socket.
OutputStream getOutputStream(
)throws IOException
Returns an output stream so that data may be written
to this socket.
void setSoTimeout(int timeout)
throws SocketException
Set a timeout period for blocking so that a read( )
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
Returns an input stream so that data may be read
from this socket.
A read operation on the InputStream is blocking.
A write operation is nonblocking.
February 14th, 2006
Integratie van Sofware Systemen
76
Connection-oriented socket API-3
client
server
1. Server establishes a
socket sd1 with local
address, then listens
for incoming
connection on sd1
2. Server accepts the
connection request
and creates a new
socket sd2 as a result.
February 14th, 2006
sd1
Client establishes
a socket with
remote (server's)
address.
sd1
sd2
Integratie van Sofware Systemen
77
Connection-oriented socket API-3
3. Server issues receive
operation using sd2.
sd1
Client issues
send operation.
sd2
4. Server sends response
using sd2.
sd1
sd2
5. When the protocol
has completed, server
closes sd2; sd1 is
used to accept the
next connection
February 14th, 2006
sd1
Integratie van Sofware Systemen
Client closes its
socket when the
protocol has
completed
78
Connectionless socket API
P1
P2
P1 establishes
a local socket
P2 establishes
a local socket
P1 issues a
receive operation
to receive the
datagram.
P2 sends a datagram
addressed to P1
February 14th, 2006
Integratie van Sofware Systemen
79
Example 4 Event Diagram
time
ConnectionAcceptor
accept
ConnectionRequestor
connect request
(from Socket constructor)
read
write
message
an operation
close
data socket
process executing
close
connection socket
close socket
February 14th, 2006
Integratie van Sofware Systemen
process suspended
80
Example4
Example4ConnectionAcceptor
try {
nt portNo;
String message;
// instantiates a socket for accepting connection
ServerSocket connectionSocket = new ServerSocket(portNo);
Socket dataSocket = connectionSocket.accept();
// get a output stream for writing to the data socket
O utputStream outStream = dataSocket.getO utputStream ();
// create a PrinterWriter object for character-mode output
PrintWriter socketO utput =
new PrintWriter(new O utputStreamWriter(outStream));
// write a message into the data stream
socketO utput.println (message);
//The ensuing flush method call is necessary for the data to
// be written to the socket data stream before the
// socket is closed.
socketO utput.flush ();
dataSocket.close ( );
connectionSocket.close ( );
} // end try
catch (Exception ex) {
System.out.println (ex);
}
February 14th, 2006
Example4ConnectionReceiver
try {
InetAddress acceptorHost =
InetAddress.getByName (args[0]);
int acceptorPort = Integer.parseInt(args[1]);
// instantiates a data socket
Socket mySocket = new Socket(acceptorHost, acceptorPort);
// get an input stream for reading from the data socket
InputStream inStream = mySocket.getInputStream ();
// create a BufferedReader object for text-line input
BufferedReader socketInput =
new BufferedReader(new InputStreamReader(inStream));
// read a line from the data stream
String message = socketInput.readLine ( );
System.out.println ("\t" + message);
mySocket.close ( );
} // end try
catch (Exception ex) {
System.out.println (ex);
}
Integratie van Sofware Systemen
81
Overview
Introduction
Connectionless datagram transport
Connection oriënted datagram transport
Streaming transport
Secure transport
Conclusions
References
February 14th, 2006
Integratie van Sofware Systemen
82
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.
February 14th, 2006
Integratie van Sofware Systemen
83
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
February 14th, 2006
Integratie van Sofware Systemen
84
Conclusions (usage)
Connectionless service:
 UDP
 JAVA Datagram Socket API
Connection Oriënted service:
 TCP
 JAVA Stream Mode Socket API
Secure Transport Service:
 SSL
 JSSE (Java Secure Socket Extension)
February 14th, 2006
Integratie van Sofware Systemen
85
References
Deitel & Deitel
“Java How to Program”
Fred Halsall
“Data communications, computer networks and open systems”
SUN
Java reference pages java.sun.com
Liu
“Distributed Computing - principles and applications”
February 14th, 2006
Integratie van Sofware Systemen
86
Self Study Exercises
Chapter 3
 Exercise 1
 Exercise 3
 Exercise 5
Chapter 4
 Exercise 1
 Exercise 2
 Exercise 9
 Exercise 11 (no report)
February 14th, 2006
Integratie van Sofware Systemen
87
Download