university of pittsburgh computer science 1 week 5: introduction last week we discussedlast week we...
TRANSCRIPT
University of Pittsburgh Computer Science
1
Week 5: IntroductionWeek 5: Introduction
• Last week we discussedLast week we discussed Difference between executing sequentially Difference between executing sequentially
and in paralleland in parallel
How multi-tasking allows computers to appear How multi-tasking allows computers to appear to do things in parallel, even with only one to do things in parallel, even with only one CPUCPU
How multi-tasking is done with Threads in JavaHow multi-tasking is done with Threads in Java Thread objects execute run() subprogramThread objects execute run() subprogram When run() finishes, thread is deadWhen run() finishes, thread is dead Moving.java and Moving1.java with one threadMoving.java and Moving1.java with one thread
Using more than one threadUsing more than one thread Independent threads – no data sharingIndependent threads – no data sharing
University of Pittsburgh Computer Science
2
Week 5: IntroductionWeek 5: Introduction
– Bounce.java demonstrationBounce.java demonstration
Threads share dataThreads share data– Data consistency issuesData consistency issues– Using monitors to restrict access to critical dataUsing monitors to restrict access to critical data
Other multi-thread issuesOther multi-thread issues– Deadlock – no thread can execute due to circular Deadlock – no thread can execute due to circular
dependency of resourcesdependency of resources– Starvation – some thread never gets to executeStarvation – some thread never gets to execute
University of Pittsburgh Computer Science
3
Week 5: Communicating with Other ComputersWeek 5: Communicating with Other Computers
Send and receive emailSend and receive email
• Computers need to “talk” to each Computers need to “talk” to each other for various reasonsother for various reasons
Upload and download filesUpload and download files
Allow multiple users to access information Allow multiple users to access information at the same timeat the same time
Ex. GamesEx. Games
• How can we do this?How can we do this?
University of Pittsburgh Computer Science
4
Week 5: Servers and ClientsWeek 5: Servers and Clients
• Typically, communicating Typically, communicating computers take on one of two roles:computers take on one of two roles:
Client: Client: computer makes requests to computer makes requests to server and utilizes the resultsserver and utilizes the results
Usually has an interface with userUsually has an interface with user
Server: Server: computer takes requests from computer takes requests from other computers and supplies them with other computers and supplies them with files, data, etcfiles, data, etc
Often does not deal directly with end Often does not deal directly with end usersusers
University of Pittsburgh Computer Science
5
Week 5: Types of CommunicationWeek 5: Types of Communication
• Computers can communicate in Computers can communicate in different waysdifferent ways Connection-oriented communicationConnection-oriented communication
Computers connect to each other and transmit Computers connect to each other and transmit data back and forthdata back and forth
Computers remain connected even if no data is Computers remain connected even if no data is sentsent
Similar in idea to a phone lineSimilar in idea to a phone line Connectionless communicationConnectionless communication Computers send Computers send data packetsdata packets to each other to each other No continuous connection between themNo continuous connection between them Similar in idea to U.S. MailSimilar in idea to U.S. Mail
University of Pittsburgh Computer Science
6
Week 5: Types of CommunicationWeek 5: Types of Communication
•Connection-oriented: all data follows the same path between the client and the server
•Connectionless: each data packet may follow a different route between client and server – no hard “connection” exists
CLIENT
SERVER
NETWORK
University of Pittsburgh Computer Science
7
Week 5: Types of CommunicationWeek 5: Types of Communication
• Advantages of connection-oriented:Advantages of connection-oriented: Data flow is consistent and reliableData flow is consistent and reliable
Order sent is always order receivedOrder sent is always order received
After set-up is complete, can be very fastAfter set-up is complete, can be very fast
• Disadvantages of connection-Disadvantages of connection-oriented:oriented: Each link in the connection is a vulnerable Each link in the connection is a vulnerable
pointpoint If a link goes down, connection must be If a link goes down, connection must be
reestablishedreestablished
Initial set-up can be time-consumingInitial set-up can be time-consuming For small amounts of data, overhead incurred For small amounts of data, overhead incurred
is too highis too high
University of Pittsburgh Computer Science
8
Week 5: Types of CommunicationWeek 5: Types of Communication
• Advantages of connectionless:Advantages of connectionless: No initial setup timeNo initial setup time
Short messages can be sent very quicklyShort messages can be sent very quickly
If a network link goes down, messages If a network link goes down, messages can easily be reroutedcan easily be rerouted
• Disadvantages of connectionless:Disadvantages of connectionless: Each packet must be routed individuallyEach packet must be routed individually
For long messages, this is time-consumingFor long messages, this is time-consuming
No guarantee that messages will arrive in No guarantee that messages will arrive in order, or even at allorder, or even at all Up to server-client to handle thisUp to server-client to handle this
University of Pittsburgh Computer Science
9
Week 5: Java SocketsWeek 5: Java Sockets
• We’ll look at connection-oriented We’ll look at connection-oriented communication in Javacommunication in Java
Utilizes Utilizes SOCKETSSOCKETS Think of these as a two-way connection Think of these as a two-way connection
between the client and the serverbetween the client and the server
Server starts up a Server starts up a ServerSocket This waits to accept a connection from a clientThis waits to accept a connection from a client
Client creates a new Client creates a new Socket by by connecting to Serverconnecting to Server Server creates a Socket on its end Server creates a Socket on its end
simultaneouslysimultaneously
University of Pittsburgh Computer Science
10
Week 5: Java SocketsWeek 5: Java Sockets
Socket
CLIENT
SERVER
Client Output
Server
Input
Server Output
Client Input
University of Pittsburgh Computer Science
11
Week 5: Java SocketsWeek 5: Java Sockets
• Let’s look at a simple exampleLet’s look at a simple example Server will wait for connection from clientsServer will wait for connection from clients
At each connection, client will send a At each connection, client will send a single message to the server, which the single message to the server, which the server will printserver will print
Server sends no data back to the clientServer sends no data back to the client Download SendToMe.java and ISend.java from Download SendToMe.java and ISend.java from
the Web sitethe Web site Start up two command promptsStart up two command prompts Compile and run SendToMe.java in the firstCompile and run SendToMe.java in the first Wait for instructions about ISend.javaWait for instructions about ISend.java
University of Pittsburgh Computer Science
12
Week 5: Java SocketsWeek 5: Java Sockets
• Computer addressesComputer addresses Computers connected directly to the internet Computers connected directly to the internet
have IP (Internet Protocol) Addresseshave IP (Internet Protocol) Addresses Technically a sequence of numbersTechnically a sequence of numbers
– Ex: 123.45.67Ex: 123.45.67
Usually accessed by nameUsually accessed by name– Ex: unixs1.cis.pitt.edu, nomad.cs.pitt.eduEx: unixs1.cis.pitt.edu, nomad.cs.pitt.edu
When connecting to a server, you must When connecting to a server, you must supply the supply the IP AddressIP Address and the and the port port numbernumber A single machine may be running many server A single machine may be running many server
programs, each on a different portprograms, each on a different port
University of Pittsburgh Computer Science
13
Week 5: Java SocketsWeek 5: Java Sockets
• Each computer in this lab has an IP addressEach computer in this lab has an IP address Names are written on the computer box and in the Names are written on the computer box and in the
CS department are CS department are hostname.cs.pitt.eduhostname.cs.pitt.edu
Look around and find out the addresses of some Look around and find out the addresses of some computers in the lab – just the first part up to the computers in the lab – just the first part up to the periodperiod
To send a message to someone else in the lab, type To send a message to someone else in the lab, type the following at the command prompt:the following at the command prompt:
java ISend hostname yourname “your message”java ISend hostname yourname “your message”
Try it a few times with various computersTry it a few times with various computers Try to guess who is sending you a messageTry to guess who is sending you a message But be nice!But be nice!
University of Pittsburgh Computer Science
14
Week 5: Java Sockets Week 5: Java Sockets
• Let’s look at the codeLet’s look at the code SendToMe.javaSendToMe.java
ServerSocket created, then goes into a loopServerSocket created, then goes into a loop Socket connection acceptedSocket connection accepted Reads a single line from client and prints it to Reads a single line from client and prints it to
consoleconsole
ISend.javaISend.java Gets host name, user name and message from Gets host name, user name and message from
command linecommand line Connects to correct host with a new socketConnects to correct host with a new socket Writes message to serverWrites message to server Closes connectionCloses connection
University of Pittsburgh Computer Science
15
Week 5: Two-Way Communication Week 5: Two-Way Communication
• In the first exampleIn the first example Client sends, server receivesClient sends, server receives
Server has simple loop, client just a few linesServer has simple loop, client just a few lines
• What if both client and server want What if both client and server want to send and receive data?to send and receive data? If sending and receiving are synchronized, If sending and receiving are synchronized,
we do not have to complicate things we do not have to complicate things muchmuch
What if server and client want to be able What if server and client want to be able to send to each other at any time?to send to each other at any time? We need to use ThreadsWe need to use Threads
University of Pittsburgh Computer Science
16
Week 5: Two-Way CommunicationWeek 5: Two-Way Communication
• Both sides of the communication must Both sides of the communication must be ready to send or receive a message be ready to send or receive a message at any timeat any time Without Threads, they could end up Without Threads, they could end up
deadlockeddeadlocked
CLIENT
SERVER
Client trying to send message to server
Server trying to send message to client
University of Pittsburgh Computer Science
17
Week 5: Two-Way CommunicationWeek 5: Two-Way Communication
• We need a way for each side to accept We need a way for each side to accept and receive messages at any timeand receive messages at any time One Thread for readingOne Thread for reading
One Thread for writingOne Thread for writing
SERVER
Client Thread waiting to accept messages Server Thread
sending messages
Server Thread waiting to accept messages
Client Thread sending messages
CLIENT
University of Pittsburgh Computer Science
18
Week 5: Two-Way CommunicationWeek 5: Two-Way Communication
• Look at next exampleLook at next example TwoWayServer.javaTwoWayServer.java
TwoWayClient.javaTwoWayClient.java
Compile TwoWayServer.javaCompile TwoWayServer.java Run with your name on command lineRun with your name on command line
– java TwoWayServer yournamejava TwoWayServer yourname– Now your computer will be a server that some Now your computer will be a server that some
other student can connect to in order to talkother student can connect to in order to talk
Compile TwoWayClient.javaCompile TwoWayClient.java Run with server name and your nameRun with server name and your name
– java TwoWayClient servername yournamejava TwoWayClient servername yourname– Where servername is the computer of another Where servername is the computer of another
student that you want to talk tostudent that you want to talk to
University of Pittsburgh Computer Science
19
Week 5: Two-Way CommunicationWeek 5: Two-Way Communication
• Let’s look at the codeLet’s look at the code Note that both programs look similarNote that both programs look similar
Threads are created for the input stream and Threads are created for the input stream and for the output streamfor the output stream
Each runs until the client/server has quitEach runs until the client/server has quit
The threads are NOT synchronized (no The threads are NOT synchronized (no monitors used)monitors used) Could cause a problem, but in this simple Could cause a problem, but in this simple
example it is not absolutely necessaryexample it is not absolutely necessary If we have more complicated communication, If we have more complicated communication,
monitors will be definitely requiredmonitors will be definitely required– Could lead to data consistency problems Could lead to data consistency problems
otherwise otherwise
University of Pittsburgh Computer Science
20
Week 5: More Complex CommunicationWeek 5: More Complex Communication
• Consider now a single server that Consider now a single server that serves many clientsserves many clients Each client connects to the serverEach client connects to the server
Clients interact with serverClients interact with server
Clients also interact with each other Clients also interact with each other through serverthrough server
Server needs to divide its time amongst Server needs to divide its time amongst clientsclients Server must coordinate interaction with Server must coordinate interaction with clients such that data is always consistentclients such that data is always consistent
University of Pittsburgh Computer Science
21
Week 5: More Complex CommunicationWeek 5: More Complex Communication
SERVER
CLIENT
CLIENT CLIENT
CLIENT
Additional links not shown
University of Pittsburgh Computer Science
22
Week 5: More Complex CommunicationWeek 5: More Complex Communication
• Server's job is quite complicatedServer's job is quite complicated Allows clients to log in and out and keeps Allows clients to log in and out and keeps
track of themtrack of them Takes messages from each client and Takes messages from each client and
passes them on to the other clients passes them on to the other clients Sees to it that clients' messages do not Sees to it that clients' messages do not
interfere with one anotherinterfere with one another "If you all talk at once, no one will understand "If you all talk at once, no one will understand
what you are saying!"what you are saying!" Server has to regulate how messages are passedServer has to regulate how messages are passed
University of Pittsburgh Computer Science
23
Week 5: More Complex CommunicationWeek 5: More Complex Communication
SERVER
CLIENT
CLIENT CLIENT
CLIENT
Hey, listen to me!
One at a time and you'll all get your turn!
No, listen to me!
No, listen to me!
No, listen to me!
University of Pittsburgh Computer Science
24
Week 5: More Complex CommunicationWeek 5: More Complex Communication
• How can we do this in Java?How can we do this in Java? The server needs to have a thread for The server needs to have a thread for
each clienteach client Each thread will in a sense serve the needs of Each thread will in a sense serve the needs of
one clientone client
The threads MUST be synchronizedThe threads MUST be synchronized There is a lot of critical data in the server that There is a lot of critical data in the server that
must only be accessed by one thread at a timemust only be accessed by one thread at a time– Updating the number of clients onlineUpdating the number of clients online– Sending a message to the clients onlineSending a message to the clients online
Let’s look at an example – a Chat ServerLet’s look at an example – a Chat Server
University of Pittsburgh Computer Science
25
Week 5: More Complex CommunicationWeek 5: More Complex Communication
• General idea:General idea: Client logs into server and is added to list of Client logs into server and is added to list of
clientsclients Client is assigned a thread in the server programClient is assigned a thread in the server program Server synchronizes client threads for data Server synchronizes client threads for data
consistencyconsistency
Client also has a thread for receiving Client also has a thread for receiving messagesmessages However, no thread used to send messages – a However, no thread used to send messages – a
Button and ActionEvent are used to process themButton and ActionEvent are used to process them They are then sent to the serverThey are then sent to the server
Client also has a GUI so that users will be Client also has a GUI so that users will be comfortablecomfortable
University of Pittsburgh Computer Science
26
Week 5: More Complex CommunicationWeek 5: More Complex Communication
• Let’s try the programLet’s try the program Download JRChatServer.javaDownload JRChatServer.java
Download JRChatClient.javaDownload JRChatClient.java
Compile and run JRChatClient.javaCompile and run JRChatClient.java
Use it for a while … log in and out … send Use it for a while … log in and out … send messages … see what is going onmessages … see what is going on
Now look at the codeNow look at the code DiscussDiscuss
University of Pittsburgh Computer Science
27
Week 5: SummaryWeek 5: Summary
• This week we discussedThis week we discussed Idea of servers and clientsIdea of servers and clients
Communication between server and Communication between server and clientsclients Connection-oriented communication with Connection-oriented communication with
socketssockets Connectionless communication with packetsConnectionless communication with packets If two-way, need for threadsIf two-way, need for threads
Using a server with multiple clientsUsing a server with multiple clients How to coordinate the clients with threads and How to coordinate the clients with threads and
monitorsmonitors