Download Chapter 18 Networking

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Proxy server wikipedia , lookup

Dynamic Host Configuration Protocol wikipedia , lookup

British telephone socket wikipedia , lookup

Transcript
Chapter 3 Inter-process Communication
Reference slides from Distributed systems concepts and design
Distributed computing Liu , and operating system concepts Silberschatz
1
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Middleware layer
This chapter is concerned with the characteristics of protocols for
communication between processes. E.g. Java API
RMI and RPC is concerned with integrating communication into a
programming language paradigm. Under RMI and RPC, there are
sockets, message passing, multicast support.
Protocols for the representation of collections of data objects in
2 messages are also discussed.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Synchronous and Asynchronous
 Synchronous and Asynchronous communication: Sending and receiving
processes may be either one of them.
 Synchronous: two processes synchronize at every message. Both send
and receive are blocking operations. Whenever a send issued the
sending process is blocked until the receive is issued. Whenever a
receive is issued by a process, it blocks until a message arrives.
 Asynchronous: The send operation is non-blocking and the sending
process is allowed to proceed as soon as the message has been copied to
a local buffer. The receive can be either blocking or nonblocking(process can proceed and notified by polling or interrupt when
background buffer filled. But no advantage due to multi-thread and
overhead of implementing the mechanism).
3
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Sockets and ports
socket
any port
agreed port
socket
message
client
server
other ports
Internet address = 138.37.94.248
Internet address = 138.37.88.249
Both UDP and TCP use the socket as endpoints for communication between
processes. A socket is associated with a Internet address and port number.
Each computer has a large number 2^16 of possible port numbers. Processes
may use the same socket for sending and receiving messages.
4
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
TCP
 TCP stream of bytes communication
 A dedicated point-to-point channel
 Use TCP (Transmission Control Protocol) for data transmission.
 For integrity, checksum is used to detect and reject corrupt packets
an sequence numbers to detect and reject duplicate packets. For
validity, timeouts and retransmission to deal with lost packets.
 So messages are guaranteed to be delivered. Lossless and reliable.
Sent and received in the same order.
Use of TCP: many frequently used services run over TCP connections
HTTP, FTP, Telnet, SMTP
5
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
UDP
 UDP datagram communication: attractive due to no overheads associated
with guaranteed message delivery
 No dedicated point-to-point channel
 Use UDP (User Datagram Protocol) for data transmission. No acknowledge and retries.
 Omission failure as messages may be dropped occasionally either because of checksum
error or no buffer space at source or destination
 Messages can be sometimes be delivered out of sender order
 So applications using UDP are left to provide their own checks to
achieve quality of reliable communication that suffers from omission
failures, which can be constructed by using acknowledgements.
 Applications that are acceptable to have occasional omission failure and
out of order. For example, DNS and Voice Over IP (VOIP)
6
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Client/Server Communications: TCP
The server must be running when a client starts.
The server waits for a connection request from a
client. To establish a server, you need to create a
server socket and attach it to a port, which is
where the server listens for connections.
Server Host
After a server
socket is created,
the server can use
this statement to
listen for
connections.
7
Server socket on port 8000
SeverSocket server =
new ServerSocket(8000);
A client socket
Socket socket =
server.accept()
After the server accepts the
connection, communication
between server and client is
conducted the same as for
I/O streams.
Client Host
I/O Stream
Client socket
Socket socket =
new Socket(host, 8000)
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
The client issues
this statement to
request a
connection to a
server.
Data Transmission through Sockets
Server
Client
int port = 8000;
DataInputStream in;
DataOutputStream out;
ServerSocket server;
Socket socket;
server =new ServerSocket(port);
socket=server.accept();
in=new DataInputStream
(socket.getInputStream());
out=new DataOutStream
(socket.getOutputStream());
System.out.println(in.readDouble());
out.writeDouble(aNumber);
int port = 8000;
String host="localhost"
DataInputStream in;
DataOutputStream out;
Socket socket;
Connection
Request
I/O
Streams
socket=new Socket(host, port);
in=new DataInputStream
(socket.getInputStream());
out=new DataOutputStream
(socket.getOutputStream());
out.writeDouble(aNumber);
System.out.println(in.readDouble());
InputStream input = socket.getInputStream();
OutputStream output = socket.getOutputStream();
8
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
A TCP Client/Server Example
 Problem: Write a client to send data to a server. The server
receives the data, uses it to produce a result, and then sends
the result back to the client. The client displays the result
on the console. In this example, the data sent from the
client is the radius of a circle, and the result produced by
the server is the area of the circle.
compute area
radius
Server
Client
area
9
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
A Client/Server Example, cont.
compute area
radius
Server
Client
area
Server Code
Client Code
Start Server
Start Client
Note: Start the server, then the client.
10
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
The InetAddress Class
Occasionally, you would like to know who is connecting to the server.You can
use the InetAddress class to find the client's host name and IP address. The
InetAddress class models an IP address.You can use the statement shown
below to create an instance of InetAddress for the client on a socket.
InetAddress inetAddress = socket.getInetAddress();
Next, you can display the client's host name and IP address, as follows:
System.out.println("Client's host name is " +
inetAddress.getHostName());
System.out.println("Client's IP Address is " +
inetAddress.getHostAddress());
11
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Serving Multiple Clients
Multiple clients are quite often connected to a single server at the same time. Typically, a
server runs constantly on a server computer, and clients from all over the Internet may want
to connect to it.You can use threads to handle the server's multiple clients simultaneously.
Simply create a thread for each connection. Here is how the server handles the establishment
of a connection:
while (true) {
Socket socket = serverSocket.accept();
Thread thread = new Thread(new ThreadClass(socket));
thread.start();
}
The server socket can have many connections. Each iteration of the while loop creates a new
connection. Whenever a connection is established, a new thread is created to handle
communication between the server and the new client; and this allows multiple connections
to run at the same time.
12
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Example: Serving Multiple Clients
Server
Server for Multiple Clients
A serve socket
on a port
A socket for a
client
A socket for a
client
Start Server
Client 1
...
Start Client
Note: Start the server first, then start multiple clients.
13
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Client n
DatagramPacket
The DatagramPacket class represents a datagram packet. Datagram packets
are used to implement a connectionless packet delivery service. Each
message is routed from one machine to another based solely on information
contained within the packet.
java.net.DatagramPacket
length: int
A JavaBeans property to specify the length of buffer.
address: InetAddress
A JavaBeans property to specify the address of the machine where the
package is sent or received.
port: int
A JavaBeans property to specify the port of the machine where the
package is sent or received.
+DatagramPacket(buf: byte[],
Constructs a datagram packet in a byte array buf of the specified length
length: int, host: InetAddress, port: with the host and the port for which the packet is sent. This constructor
int)
is often used to construct a packet for delivery from a client.
+DatagramPacket(buf: byte[],
length: int)
Constructs a datagram packet in a byte array buf of the specified length.
+getData(): byte[]
Returns the data from the package.
+setData(buf: byte[]): void
14
Sets the data in the package.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
DatagramSocket
DatagramSocket The DatagramSocket class represents a socket for sending and receiving
datagram packets. A datagram socket is the sending or receiving point for a
packet delivery service. Each packet sent or received on a datagram socket
is individually addressed and routed. Multiple packets sent from one
machine to another may be routed differently, and may arrive in any order.
To create a server DatagramSocket, use the constructor DatagramSocket(int
Create a server port), which binds the socket with the specified port on the local host
DatagramSocket machine.
To create a client DatagramSocket, use the constructor DatagramSocket(),
Create a client
which binds the socket with any available port on the local host machine.
DatagramSocket
15
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Sending and Receiving a DatagramSocket
Sending
Receiving
16
To send data, you need to create a packet, fill in the contents,
specify the Internet address and port number for the receiver,
and invoke the send(packet) method on a DatagramSocket.
To receive data, create an empty packet and invoke the
receive(packet) method on a DatagramSocket.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Datagram Programming
Datagram programming is different from stream socket programming in the
sense that there is no concept of a ServerSocket for datagrams. Both client and
server use DatagramSocket to send and receive packets.
Designate
on a server
DatagramServer
DatagramClient
DatagramSocket socket;
socket = new DatagramSocket(8000);
DatagramSocket socket;
socket = new DatagramSocket();
byte[] buf = new byte[256];
byte[] buf = new byte[256];
DatagramPacket receivePacket = new
DatagramPacket(buf, bef.length)
InetAddress address = new
InetAddress(serverName);
socket.receive(receivePacket);
DatagramPacket sendPacket = new
DatagramPacket(buf, bef.length, address, 8000)
get data from buf or receivePacket.getData();
fill in the contents in buf;
socket.send(sendPacket);
17
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Example: A Client/Server Example
Already present a client program and a server program using socket
streams. The client sends radius to a server. The server receives the
data, uses them to find the area, and then sends the area to the client.
Rewrite the program using datagram sockets.
18
Server Code
Client Code
Start Server
Start Client
Note: Start the server,
then the client.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Client/Server Communications
 Both forms of communication UDP and TCP use the socket
abstraction, which provides endpoint for communication
between processes.
 Each socket is associated with a particular protocol either
UDP or TCP.
Each Internet host has 2^16 (65,535) logical ports. Each
port is identified by a number between 1 and 65535, and can
be allocated to a particular process.
Port numbers between 1 and 1023 are reserved for processes
which provide well-known services such as finger, FTP,
HTTP, and email.
19
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Ports Assignment
Assignment of some well-known ports
20
Protocol
Port
Service
echo
7
IPC testing
daytime
13
provides the current date and time
ftp
21
file transfer protocol
telnet
23
remote, command-line terminal session
smtp
25
simple mail transfer protocol
time
37
provides a standard time
finger
79
provides information about a user
http
80
web server
RMI Registry
1099
registry for Remote Method Invocation
special web server
8080
web server which supports
servlets, JSP, or ASP
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Case Studies: Distributed TicTacToe
Games
Server
Session 1
Player 1
21
Player 2
...
...
Session N
Player 1
TicTacToeServer
Run Server
TicTacToeClient
Run Client
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Player 2
Distributed TicTacToe Game
Player 1
Server
1. Initialize user interface.
Create a server socket.
2. Request connection to the server and
know which token to use from the server.
Accept connection from the first player and notify the player
is Player 1 with token X.
Accept connection from the second player and notify the
player is Player 2 with token O. Start a thread for the
session.
Player 2
1. Initialize user interface.
2. Request connection to the server and
know which token to use from the server.
Handle a session:
3. Get the start signal from the server.
4. Wait for the player to mark a cell, send
the cell's row and column index to the
server.
5. Receive status from the server.
6. If WIN, display the winner; if player 2
wins, receive the last move from player 2.
Break the loop
7. If DRAW, display game is over; break
the loop.
1. Tell player 1 to start.
2. Receive row and column of the selected cell from
Player 1.
3. Determine the game status (WIN, DRAW,
CONTINUE). If player 1 wins, or drawn, send the status
(PLAYER1_WON, DRAW) to both players and send
player 1's move to player 2. Exit.
.
4. If CONTINUE, notify player 2 to take the turn, and
send player 1's newly selected row and column index to
player 2.
5. Receive row and column of the selected cell from
player 2.
6. If player 2 wins, send the status (PLAYER2_WON) to
both players, and send player 2's move to player 1. Exit.
8. If CONTINUE, receive player 2's
selected row and column index and mark
the
22cell for player 2.
7. If CONTINUE, send the status, and send player 2's
newly selected row and column index to Player 1.
3. Receive status from the server.
4. If WIN, display the winner. If player 1
wins, receive player 1's last move, and
break the loop.
5. If DRAW, display game is over, and
receive player 1's last move, and break the
loop.
6. If CONTINUE, receive player 1's
selected row and index and mark the cell
for player 1.
7. Wait for the player to move, and send
the selected row and column to the server.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Distributed TicTacToe, cont.
JFrame
-char
token
TicTacToeServer
-
HandleASession
-
TicTacToeConstants
+getToke
-char token n
+setToke
JApplet
+getToken n
+setToken +paintCo
-char
+paintComponet
mponet
token
+mouseClicked
Runnable
+mouseC
licked
+getToke
-char token n
+setToke
+getToken
TicTacToeServer
n
+setToken +paintCo
+paintComponet
mponet void
+main(args: String[]):
+mouseClicked
+mouseC
licked
TicTacToeConstants
+PLAYER1=1: int
+PLAYER2 = 2: int
+PLAYER1_WON = 1: int
+PLAYER2_WON = 2: int
+DRAW = 3: int
+CONTINUE = 4: int
23
Similar as in
Example 12.7
TicTacToeClient
-
Cell
-
-
HandleASession
-player1: Socket
-player2: Socket
-cell char[][]
-continueToPlay: boolean
+run(): void
-isWon(): boolean
-isFull(): boolean
-sendMove(out:
DataOuputStream, row: int,
column: int): void
TicTacToeClient
-myTurn: boolean
-myToken: char
-otherToken: char
-cell: Cell[][]
-continueToPlay: boolean
-rowSelected: int
-columnSelected: int
-isFromServer: DataInputStream
-osToServer: DataOutputStream
-waiting: boolean
+run(): void
-connectToServer(): void
-recieveMove(): void
-sendMove(): void
-receiveInfoFromServer(): void
-waitForPlayerAction(): void
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Synchronization Revisit
Message passing may be either blocking or non-blocking
 Blocking is considered synchronous
 Blocking send has the sender block until the corresponding receive is
issued
 Blocking receive has the receiver block until a message arrives
 Non-blocking is considered asynchronous
 Non-blocking sender proceeds after send operation (message is copied to
local buffer). So the message transmission can run parallel with the sender
program
 Non-blocking receiving process proceeds after receive operation, which
provides a buffer to be filled in the background. But it must separately
receive notification that its buffer has been filled by polling or interrupt


24
In multiple thread process, blocking receive has no disadvantage. Simple
synchronization and less complexity. So today system do not generally provide nonblocking receive.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Buffering
 Queue of messages attached to the link; implemented in
one of three ways
1. Zero capacity – 0 messages
Sender must wait for receiver (rendezvous)
2. Bounded capacity – finite length of n messages
Sender must wait if link full
3. Unbounded capacity – infinite length
Sender never waits
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Remote Procedure Calls
 Remote procedure call (RPC) abstracts procedure calls
between processes on networked systems.
 Stubs – client-side proxy for the actual procedure on the
server.
 The client-side stub locates the server and marshalls the
parameters.
 The server-side stub receives this message, unpacks the
marshalled parameters, and performs the procedure on
the server.
26
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Marshalling Parameters
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Remote Method Invocation
 Remote Method Invocation (RMI) is a Java mechanism
similar to RPCs.
 RMI allows a Java object on one machine to invoke a
method on a remote object.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
External Data Representation and
marshalling
 Data transmitted on the network is a binary stream.
 Because different computers may have different internal storage
format for the same data type, an external representation of data may
be necessary.
 Data marshalling is the process of translating/ converting the data to
an external representation.
 Data unmarshalling is the process of rebuilding of data structure.
 Three approaches to external data representation schemes are:
a. CORBA’s common data representation: can represent all data
types for argument and return values for RMI in CORBA for a variety
of programming languages.
b. Java’s object serialization: flatterning of an object into a serial form
that can be transmitted in a message and stored on disk. It is for use only by
Java. Types information is included.
c. XML (Extensible Markup Language): define a self-describing textual
format for structured data for web use.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Example: Person Object
 Struct Person {
 String name;
 String place;
 Unsigned long year;
};
30
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
CORBA Common Data Representation
(CDR) message
index in
sequence of bytes
0–3
4–7
8–11
12–15
16–19
20-23
24–27
The flattened form represents a
4 bytes
5
"Smit"
"h___"
6
"Lond"
"on__"
1934
notes
on representation
length of string
‘Smith’
length of string
‘London’
unsigned long
Person struct with value: {‘Smith’, ‘London’, 1934}
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Java serialized form
public class Person implements Serializable {
private String name;
private String place;
private int year;
public Person() {
}
}
Serialized values
Person
8-byte version number
h0
Explanation
class name, version number
3
int year
java.lang.String java.lang.String number, type and name of
name:
place:
instance variables
1934
5 Smith
6 London
h1
values of instance variables
The true serialized form contains additional type markers; h0 and h1 are handles
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
XML definition of the Person structure
<person id="123456789">
<name>Smith</name>
<place>London</place>
<year>1934</year>
<!-- a comment -->
</person >
Elements: portion of character data surrounded by start and end tag. Hierarchical
structure is possible with element enclosing.
Attributes: start tag may include associated attribute names and values. E.g.
id=“123456789”
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Example: Passing Objects in Network Programs
Write a program that
collects student
information from a client
and send them to a
server. Passing student
information in an object.
Client
Server
student object
student object
in.readObject()
out.writeObject(student)
in: ObjectInputStream
out: ObjectOutputStream
socket.getInputStream
socket.getOutputStream
socket
socket
Student Class
Network
Student Sever
Student Client
Start Server
Start Client
Note: Start the server first, then the client.
34
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Secure Sockets
 Secure sockets perform encryption on the data




35
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.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671
Secure Sockets
 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.
 Example code available:
 http://java.sun.com/javase/6/docs/technotes/guides
/security/jsse/JSSERefGuide.html#UnsecureSecure
36
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All
rights reserved. 0136012671