Practicum: - Client-Server Computing in Java 15-211 Fundamental Data Structures and Algorithms...
-
Upload
arabella-wilkerson -
Category
Documents
-
view
237 -
download
0
Transcript of Practicum: - Client-Server Computing in Java 15-211 Fundamental Data Structures and Algorithms...
Practicum:- Client-Server Computing in Java
15-211 Fundamental Data Structures and Algorithms
Margaret Reid-Miller
13 April 2004
2
Reminders
HW7 is out!
due on Wednesday, April 28, 11:59pm
Read:
Chapter 10
Intro toDistributed Computing
Concepts
4
Distributed computing
Many applications involve coordinated computation by multiple host computers
World-Wide WebInternet Chess ClubAndrew File SystemE-Mail servicesX Windows…
5
The client-server paradigm
Almost all modern distributed computing applications are organized around the client-server paradigm
Client initiates communicationsends requests and receives responses interacts with one (or a small number) of
servers at a time
Serverwaits and listens for incoming requests receives requests and sends responses is “always” running interacts with many clients concurrently
6
Network communication
Network communication is organized into layershardware 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
7
Network layers
Application
Protocol
Hardware
Application
Protocol
Hardware
network
protocol
data flow
8
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.
9
Hardware layer
Typically Ethernet-based
Data is transmitted in small packets typically less than 1500 bytespackets 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
10
Protocol layer
There are two main protocols usedboth provide Internet addressing/routing
TCPTransmission Control Protocolconnection (“session”) orientedprovides long data messages (via
fragmentation and reassembly of packets)provides reliable communication
UDPUnreliable Datagram Protocolnot connection orientedno transmission guarantees, but very
lightweight and efficient
11
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
12
Network layers
Application
Protocol
Hardware
Application
Protocol
Hardware
network
protocol
data flow
13
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)
14
Socket communication
process
writeread socket
process
read writesocket
network
Host Host
Sockets provide a bi-directional communication channel from one process to another.
Messages are queued• at sending socket until transmitted across the network and• at receiving socket until received by the receiving process.
15
Sockets in Java
Java provides very good support for sockets in the java.net.* package
java.net.Socketcreate: constructor methods (to create sockets) I/O: getOutputStream(), getInputStream()destroy: close()
java.net.ServerSocketcreate: constructor methodswait and listen: accept()destroy: close()
16
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
17
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
18
Client-server interaction
listenSocket = ServerSocket(port)
connectionSocket = listenSocket.accept()
read request(s) from connectionSocket
write reply(s) to connectionSocket
connectionSocket.close()
clientSocket = Socket(hostid,port)
send request(s) to clientSocket
read reply(s) from clientSocket
clientSocket.close()
Server
Client
TCPsession
19
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.
20
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.
21
Open Socket
Server side:
ServerSocket listenSocket = new ServerSocket(portNumber);
while (true) { Socket connectionSocket = listenSocket.accept();
…}
Client side:
Socket clientSocket = new Socket(hostId, portNumber);
Same port number
22
Create I/O streams
Client and server: E.g., character streams
BufferedReader in = new BufferedReader( new InputStreamReader( theSocket.getInputStream()));
PrintWriter out = new PrintWriter( theSocket.getOutputStream(), true);
Buffering wrapper for efficiency
Automatically flush with println
23
Client-Server Communication
Client side:
out.println(request);
reply = in.readLine();
Server side:
request = in.readLine();…reply = …out.println(reply);
24
Cleanup
Client and Server:
out.close(); in.close(); theSocket.close();
Example:A Pig Latin Server
26
Client-server interaction
listenSocket = ServerSocket(port)
connectionSocket = listenSocket.accept()
read request(s) from connectionSocket
write reply(s) to connectionSocket
connectionSocket.close()
clientSocket = Socket(hostid,port)
send request(s) to clientSocket
read reply(s) from clientSocket
clientSocket.close()
Server
Client
TCPsession
27
Example: Java client
import java.io.*;import java.net.*
public class Client { public static void main (String argv[]) throws Exception { BufferedReader user = new BufferedReader(…);
Socket clientSocket = new Socket(“foo.cs.cmu.edu”, 6789);
PrintWriter out = new PrintWriter( clientSocket.getOutputStream(),true); …
create user input stream
connect to the server
create socket output stream
28
Java client, cont’d
…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();
create socket input stream
send request to the server
read reply from server
release the connection
29
Example: Java server
import java.io.*;import java.net.*
public class Server { public static void main (String argv[]) throws Exception { ServerSocket listenSocket = new ServerSocket(6789);
while (true) { Socket connectionSocket = listenSocket.accept();
BufferedReader in = new BufferedReader( new InputStreamReader( connectionSocket.getInputStream()));
create listening socket
wait for client contact
create socket input stream
on host foo.cs.cmu.edu:
30
Java server, cont’d
PrintWriter out = new PrintWriter( connectionSocket.getOutputStream(),true);
clientSentence = in.readLine();
String pigLatin = pigTranslate(clientSentence);
out.println(pigLatin);
in.close(); out.close(); connectionSocket.close();}
create socket output stream
read request from client
service the request
send reply to client
end of while loop; go back and wait for another request
31
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
32
Exception handling
…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) { … }}
this is always executed, no matter what
33
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
34
Example: multithreaded server
import java.io.*;import java.net.*
public class Server extends Thread { ServerSocket listenSocket;
public Server () { try { listenSocket = new ServerSocket(6789); } catch (IOException e) { … }
this.start(); }…
create listening socket
start main server loop thread for it
on host foo.cs.cmu.edu:
35
Multithreaded server, cont’d
…public void run() { try { while (true) { Socket connectionSocket = listenSocket.accept();
Connection c = Connection(connectionSocket);
…
run() is invoked by start()
accept a connection
create a new thread to serve client