22
REVIEW • On Friday we explored Client-Server Applications with Sockets. • Servers must create a ServerSocket object on a specific Port #. They then can wait for connections using the accept( ) method. • The accept method returns the actual Socket object used by the server to communicate with the client.

REVIEW On Friday we explored Client-Server Applications with Sockets. Servers must create a ServerSocket object on a specific Port #. They then can wait

Embed Size (px)

Citation preview

REVIEW

• On Friday we explored Client-Server Applications with Sockets.

• Servers must create a ServerSocket object on a specific Port #. They then can wait for connections using the accept( ) method.

• The accept method returns the actual Socket object used by the server to communicate with the client.

Review

• The Client side of your program needs only to open a Socket.

• It does this by creating a new Socket object and passing both an IP address ( for us we will use 127.0.0.1 (the localhost)) as well as a port number (the same port number the server is bound to).

• Both the client and server communicate via their Sockets using a Printwriter (to send info) or a BufferedReader (to receive info).

Multitasking

Doing more than one thing at a time…

Threads

• Until now, every program you have written has had a single “thread” of control.

• This simply means that if you could stop time at any particular instant your program would be in the process of executing one and only one instruction.

• Today, many programs have multiple threads of control at any given time. This makes them more efficient.

Threads

• Consider a program such as a word processor. While you print your large document you can continue to edit your text.

• Similarly, a web server should be able to handle many different requests from many different users at the same time.

• Many programs will use one thread for the GUI and another to carry out the user’s requests.

Threads in Java

• Our Client-Server model is often implemented using a “multithreaded” server.

• If we implement our Server using only one thread then what happens if multiple clients try to connect? Think about it – what happens?

Threaded Servers

• What happens is the first client will connect to the server and have its complete attention.

• The other clients will have to wait.• If the first client has a very long request or

many different requests then the others may wait a long time to get the server’s attention.

• Imagine if a web server worked like that….

Multithreading

• To get around this problem, programmers often code their servers so that they are multithreaded.

• Each new client gets its own thread to handle its requests.

• A web server for example can handle many different clients at one time rather than making all but one wait for service.

Threads

• Before we look at implementing a multithreaded server we will take a look at how to implement threads in general and try to see how they work….

• There are two ways to make a class multithreaded. Which of the two ways we use depends upon the particular class we are considering.

Extending the Thread Class

• If the class we wish to multithread does not inherit from another class ( that is, if it does NOT extend a class) then we can simply have our new class extend the Java class Thread.

• We’ve seen this idea of extending a class when we looked at building GUIs and extended the JPanel class.

Extending the Thread class• Below is a sample of what our class declaration will

look like…

public class SimpleThread extends Thread { private int name;

public SimpleThread(int x) { name = x; } // constructor

public int getname( ){ return ( name );}

Extending Thread classRun method is called when Thread is startedpublic void run() { for (int i = 1; i <= 10; i++) { System.out.println(“ Turn “ + i + " Thread number " + getName()); try { sleep((int)(Math.random() * 1000)); } catch (InterruptedException e) {// do nothing} } // end for loop System.out.println("DONE! Thread number " + getName()); } // end run method

Thread Example• We can use the following Main method to test our

simpleThread class.public static void main( String args[ ]){ SimpleThread th = null; for (int i = 0; i < 10; i++ ) { th = new SimpleThread( i ); th.start(); // calls the run( ) method of the thread }}// This program creates 10 threads and starts em running

Thread Example

• Our program creates and starts 10 Threads (named 0-9).

• The threads then each begin executing when the main calls start( ) on them.

• Each thread is written to go through 10 turns where they print the turn # and their name.

• The threads “sleep” for a random period of time before they wake up and do the next turn.

Thread exmple• So if we look at any single thread (say Thread 5) it

simply should printTurn 1 Thread Number 5Turn 2 Thread Number 5…Turn 10 Thread Number 5DONE! Thread Number 5BUT all ten threads (0-9) are running at once! So

our output should be mixed up between all threads. Let’s try it and see what we get…

Second Example – Simple Server

• Our second example will build a simple multithreaded server.

• We will use our High-Low guessing game program turn it into multithreaded server capable of playing the game with as many clients as we wish to start up.

Threaded Servers

• The basic idea of a threaded server is to have the server program listen at its port and when a connection comes in it should take the resulting Socket object and pass it along to the constructor of a new threaded object to actually play the game with the client.

• The server then returns to listen for further connections while the thread plays the game with the client/user.

Single Client Guessing Game

• Let’s take a look at the solution for the single client version we worked on last time…

• Ask about anything that doesn’t make sense or is not clear!!!

Threaded Guessing server

• We’ll use two classes.• The first will bind to port 4321 and listen for

connections. Once a client connects, this server will create a new thread and pass it the Socket object and will then go back to listening for more connections.

• The threaded class will receive a Socket and will actually carry out the game itself with the given client.

Implementing runnable

• As mentioned earlier, extending the Thread class only works if our class does not already extend some other class – this is because Java only allows a class to extend one class.

• To get around this stupid design choice, Java does allow us to “implement” an interface. You saw this when you played around with Graphics.

• This causes us a problem when we wish to make a class Threaded but it already extends something like say JPanel or something similar.

Runnable

• To Thread an already extended class simply have the class implement the runnable interface and add a run( ) method just as we saw in our earlier examples.

• We create an object of the class and then pass it to the constructor for Thread( ). The resulting Thread object can then be “started” via the .start( ) method.

Runnable Class Example

class runexpl implements Runnable { // run() method is called when the thread runs public void run() { //do stuff here } } // below is how we’d use itrunexpl runnable = new runexpl(); // Create the thread supplying the runnable object

Thread mythread = new Thread(runnable); // Start the thread mythread.start();