Serving multiple clients Assignment Help

Assignment Help: >> Internet programming In Java >> Serving multiple clients

Serving multiple clients:

The server implementation in the previous section has a potentially serious problem: it deals with client connection requests one at a time.

In general, servers can have many clients requesting service at the same time. If a second client makes a connection request when a first client is being processed, then the second client will be queued and will be connected only when the first client has terminated its processing with the server. If the user of the first client is making infrequent service requests then it may be a long time before any other client is able to connect. At its most serious, there may be many clients queued and the server may reach its maximum queue size and disallow any more connections. In order to overcome this problem the code for the server should use threads.

Each connection that is accepted by the server should be handled by a separate thread. In this way, a number of threads could carry out the processing simultaneously. The first part of the code for a threaded class that handles a connection is shown below:

public class ConnectionThread implements Runnable
{
private Socket socket;
private HashMap nameDatabase;

// streams for connections private InputStream is;

private OutputStream os;

// writers and readers for communication
private PrintWriter toClient;
private BufferedReader fromClient;

// protocol definitions
static final String CLIENT_QUITTING = "Exit";
static final String USER_NOT_FOUND = "User not known";

public ConnectionThread (Socket s, HashMap nameData)
{
socket = s;
nameDatabase = nameData;

public void run ( )
{
try
{
openStreams( );

processClientRequests( );

closeStreams( );
socket.close( );
}
catch (Exception e)
{
System.out.println("Trouble with a connection " + e);
}
}

The most important part of the code is the run method, which contains similar code to that used in the run method of the server in the previous section. As before, this opens the input and output streams for the socket, processes the requests from this client and finally closes all the streams when the client has terminated.

The helper methods openStreams, processClientRequests and closeStreams are exactly the same as before, except that they are now private methods of the ConnectionThread class instead of being part of the NameServer class.

The main difference is that, since this is a threaded class, there may be a number of instances of this class running, each managing the connection to a different client and processing that client's requests.

Note also, the role of the constructor of the ConnectionThread class - it has two parameters that provide references to the socket to be used and the name database to which all threads must refer. These references are stored in instance variables by the constructor. We will see below where these references come from.

We also define a class called ThreadedNameServer to carry out initialization of the server and to control the creation of the ConnectionThread objects. The code for this class is as follows:

public class ThreadedNameServer
{
private HashMap nameDatabase;
private Thread connection;

// use a high numbered non-dedicated port
static final int PORT_NUMBER = 3000;

// constructor
public ThreadedNameServer ( )
{
System.out.println("... Name Server starting up");
nameDatabase = setUpNameDatabase( );
} // end constructor

// set up name database and add sample data
private HashMap <String, String> setUpNameDatabase ( )
{
HashMap <String, String> db = new HashMap <String, String>( );

db.put("Gareth Williams", "[email protected]");

db.put("Robert Thomas", "[email protected]");

db.put("William Wilson", "[email protected]");

db.put("Anne Land", "[email protected]");
db.put("Dave Phillips", "[email protected]");
db.put("Kirsten Davis", "[email protected]");

return db;
}

// loop endlessly waiting for client connections

public void run ( )
{
// establish a ServerSocket try
{
ServerSocket ss = new ServerSocket(PORT_NUMBER);
while (true)
{
// wait for a connection request
Socket socket = ss.accept( );
connection = new Thread(new ConnectionThread
(socket, nameDatabase));
connection.start( );
}
}
catch (Exception e)
{
System.out.println("Trouble with a connection " + e);
}
} // end method run
} // end class

The run method for the ThreadedServer class is similar in structure to the run method for the NameServer class in the previous section. The main difference is that client connections are not dealt with directly - a separate thread is created to handle the connection and communication with each client. We have thus separated the task of listening for new clients from the task of actually dealing with each client.

The main task of class ThreadedNameServer is now to do the listening, and to set up a thread for each client. Each thread is created using the ConnectionThread class, discussed earlier. The ConnectionThread constructor is passed two arguments: a reference to the socket that links to the client, and a reference to the name database. This ensures that the thread can communicate independently with this client, and can access the same name database as any other threads.

The start method of the thread object is invoked and it begins to execute independently. As for all threaded classes in Java, starting the thread executes the run method of the threaded object, in this case the run method of the ConnectionThread object, which handles all the communication with a particular client. The main server loop then returns to wait for another connection request.

Again, we also require a class containing a main method, which can be used to create and run the ThreadedNameServer object. A suitable class, called TestThreadedNameServer, is as follows:

public class TestThreadedNameServer
{
public static void main (String [] args)
{
ThreadedNameServer server1 = new ThreadedNameServer( );
server1.run( );
} // end main
}

The main method creates a ThreadedNameServer object and invokes its run method. This causes the server to set up the name database and then to wait for suitable clients to connect. As each client connects, a new ConnectionThread object is created to handle that client. In this way, the server can handle many clients at once, in a responsive way. The number of clients is typically limited only by the resources of the system such as the amount of memory required, or the fact that response time increases with each new client, since the threads are sharing the system processor.

The case for threading has been presented using an extreme example: that of an unthreaded server with clients that take a long time to complete their requests. Even when the duration of a client connection is short there is a compelling requirement for threading to ensure a responsive service to multiple clients. This means that virtually all servers are threaded.

 

Java Assignment Help - Java Homework Help

Struggling with java programming language? Are you not finding solution for your Serving multiple clients homework and assignments? Live Serving multiple clients experts are working for students by solving their doubts & questions during their course studies and training program. We at Expertsmind.com offer Serving multiple clients homework help, java assignment help and Serving multiple clients projects help anytime from anywhere for 24x7 hours. Computer science programming assignments help making life easy for students.

Why Expertsmind for assignment help

  1. Higher degree holder and experienced experts network
  2. Punctuality and responsibility of work
  3. Quality solution with 100% plagiarism free answers
  4. Time on Delivery
  5. Privacy of information and details
  6. Excellence in solving java programming language queries in excels and word format.
  7. Best tutoring assistance 24x7 hours

 

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd