LectureClientServerM..

Download Report

Transcript LectureClientServerM..

Practicum:
- Client-Server Computing in Java
15-211
Fundamental Data Structures and
Algorithms
Margaret Reid-Miller
13 April 2004
Reminders
 HW7 is out!
due on Wednesday, April 28, 11:59pm
 Read:
Chapter 10
2
Intro to
Distributed Computing
Concepts
Distributed computing
 Many applications involve
coordinated computation by multiple
host computers
World-Wide Web
Internet Chess Club
Andrew File System
E-Mail services
X Windows
…
4
The client-server paradigm
 Almost all modern distributed computing
applications are organized around the
client-server paradigm
 Client
 initiates communication
 sends requests and receives responses
 interacts with one (or a small number) of
servers at a time
 Server
 waits and listens for incoming requests
 receives requests and sends responses
 is “always” running
 interacts with many clients concurrently
5
Network communication
 Network communication is organized into
layers
 hardware layer
 network interface device, connected to a local area
network, which in turn is connected to a (packet
switched) Internet
 protocol layer(s)
 basic data transport mechanisms, providing
addressing (eg, IP addresses),
fragmention/reassembly, reliable transmission
 application layer
 client and server functionality
 Unconcerned with data movement across network
6
Network layers
Application
Application
Protocol
Protocol
Hardware
Hardware
network
protocol
data flow
7
Network layering
 Decomposes network communication into
simpler tasks.
 Each layer provides information hiding
from layers above and below.
 The data flow is from the application level
down the hierarchy, across the network,
and back up the hierarchy to the peer
application.
 Appears as though each layer
communicates with its peer at the same
layer.
8
Hardware layer
 Typically Ethernet-based
 Data is transmitted in small packets
 typically less than 1500 bytes
 packets are easily lost, and often arrive in
unpredictable order
 Each packet contains routing information
 A network device watches for packets that
are addressed to itself, ignores the rest
 Routers look for packets that are not
addressed to local hosts, and forwards
them to a non-local network router
9
Protocol layer
 There are two main protocols used
 both provide Internet addressing/routing
 TCP
 Transmission Control Protocol
 connection (“session”) oriented
 provides long data messages (via
fragmentation and reassembly of packets)
 provides reliable communication
 UDP
 Unreliable Datagram Protocol
 not connection oriented
 no transmission guarantees, but very
lightweight and efficient
10
Application layer
 The hardware and protocol layers are
studied in 15-441
 Here, we will focus on the application level
 Most networking applications use a
particular data structure, the socket
 A socket provides a high-level abstract
interface to a lower-level network protocol
service
 In Java, sockets are similar in some respects
to input/output streams
11
Network layers
Application
Application
Protocol
Protocol
Hardware
Hardware
network
protocol
data flow
12
Sockets
 Sockets have a long history in network
and operating system design
 first appeared in BSD 4.1 Unix in 1981
 Socket characteristics
 applications explicitly create, use, and destroy
sockets
 distinction between client sockets and server
sockets
 different kinds of sockets, depending on the
transport protocol (TCP vs UDP)
13
Socket communication
Sockets provide a bi-directional communication
channel from one process to another.
process
write
read
Host
process
network
socket
read
write
socket
Host
Messages are queued
• at sending socket until transmitted across the network and
• at receiving socket until received by the receiving
process.
14
Sockets in Java
 Java provides very good support for sockets
in the java.net.* package
 java.net.Socket
 create: constructor methods (to create sockets)
 I/O: getOutputStream(), getInputStream()
 destroy: close()
 java.net.ServerSocket
 create: constructor methods
 wait and listen: accept()
 destroy: close()
15
Socket programming with TCP
 Client must contact the server
server must first be waiting and
listening
server must thus have created a socket
that accepts client connection request
 Client contacts server by:
creating its own client TCP socket
 uses IP address and port number of server
16
Socket programming, cont’d
 When client creates its socket, a TCP
session with the server’s TCP is
established
 On the server side:
when contacted by the client, the server
TCP creates a new socket for
communication with the client
thus, each client session gets its own
private socket on the server
17
Client-server interaction
Server
listenSocket =
ServerSocket(port)
connectionSocket =
listenSocket.accept()
read request(s) from
connectionSocket
write reply(s) to
connectionSocket
Client
TCP
session
clientSocket =
Socket(hostid,port)
send request(s) to
clientSocket
read reply(s) from
clientSocket
connectionSocket.close()
clientSocket.close()
18
Client Steps
1. Open a socket.
2. Create input and output streams.
3. Send request(s) and receive
reply(s) according to the server
application protocol.
4. Close streams and socket.
19
Server steps
1. Create a server socket to listen for
connection requests.
2. Open a socket to communicate with
client.
3. Open input and output streams.
4. Accept requests and send replies.
5. Close streams and socket.
20
Open Socket
 Server side:
ServerSocket listenSocket =
new ServerSocket(portNumber);
while (true) {
Socket connectionSocket =
listenSocket.accept();
…
}
 Client side:
Same port
number
Socket clientSocket =
new Socket(hostId, portNumber);
21
Create I/O streams
 Client and server: E.g., character
streams
Buffering wrapper
for efficiency
BufferedReader in =
new BufferedReader(
new InputStreamReader(
theSocket.getInputStream()));
Automatically
PrintWriter out =
flush with println
new PrintWriter(
theSocket.getOutputStream(), true);
22
Client-Server Communication
 Client side:
out.println(request);
reply = in.readLine();
 Server side:
request = in.readLine();
…
reply = …
out.println(reply);
23
Cleanup
 Client and Server:
out.close();
in.close();
theSocket.close();
24
Example:
A Pig Latin Server
Client-server interaction
Server
listenSocket =
ServerSocket(port)
connectionSocket =
listenSocket.accept()
read request(s) from
connectionSocket
write reply(s) to
connectionSocket
Client
TCP
session
clientSocket =
Socket(hostid,port)
send request(s) to
clientSocket
read reply(s) from
clientSocket
connectionSocket.close()
clientSocket.close()
26
Example: Java client
import java.io.*;
import java.net.*
create user
input stream
connect to
the server
public class Client {
public static void main (String argv[])
throws Exception {
BufferedReader user =
new BufferedReader(…);
Socket clientSocket =
new Socket(“foo.cs.cmu.edu”, 6789);
create socket
output stream
PrintWriter out = new PrintWriter(
clientSocket.getOutputStream(),true);
…
27
Java client, cont’d
create socket
input stream
send request
to the server
read reply
from server
release the
connection
…
BufferedReader in =
new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
String sentence = user.readLine();
out.println(sentence);
String pigLatin = in.readLine();
System.out.println(“Server says:” +
pigLatin);
in.close(); out.close();
clientSocket.close();
28
Example: Java server
on host foo.cs.cmu.edu:
import java.io.*;
import java.net.*
public class Server {
create listening public static void main (String argv[])
throws Exception {
socket
ServerSocket listenSocket =
new ServerSocket(6789);
wait for
client contact
while (true) {
Socket connectionSocket =
create socket
listenSocket.accept();
input stream
BufferedReader in =
new BufferedReader(
new InputStreamReader(
connectionSocket.getInputStream()));
29
Java server, cont’d
create socket
output stream
read request
from client
service the
request
PrintWriter out =
new PrintWriter(
connectionSocket.getOutputStream(),true);
clientSentence = in.readLine();
String pigLatin =
pigTranslate(clientSentence);
out.println(pigLatin);
send reply
to client
in.close(); out.close();
connectionSocket.close();
}
end of while loop; go back and
wait for another request
30
Practical issue: cleaning up
 Closing connections
It is important to close connections
 usually a strict limit on the number of open
connections
This means it is very important to
handle exceptions, in case the socket
creation or I/O fail
 exception handler should close any open
connections
31
Exception handling
this is always
executed, no
matter what
…
try {
Socket clientSocket =
new Socket(“foo.cs.cmu.edu”, 6789);
…
} catch (UnknownHostException e) {
System.err.println(
“Couldn’t find the server host!”);
} catch (IOException e) {
System.err.println(
“I/O error!”);
} finally {
try {
if (clientSocket != null) {
out.close();
in.close();
clientSocket.close();
} } catch (IOException e) { … }
}
32
Practical issue: concurrency
 A TCP server usually must be
designed to handle multiple clients
concurrently
 This means that the server should be
set up so that the multiple copies of
the main server loop can be running
at the same time
 Java provides a mechanism for such
separate “threads” of control, in
java.lang.Thread
33
Example: multithreaded server
on host foo.cs.cmu.edu:
import java.io.*;
import java.net.*
create listening
socket
public class Server extends Thread {
ServerSocket listenSocket;
public Server () {
try {
listenSocket =
new ServerSocket(6789);
} catch (IOException e) { … }
start main
server loop
thread for it
this.start();
}
…
34
Multithreaded server, cont’d
run() is invoked
by start()
accept a
connection
create a new thread
to serve client
…
public void run() {
try {
while (true) {
Socket connectionSocket =
listenSocket.accept();
Connection c =
Connection(connectionSocket);
…
35