Advertisement

11.10.2008 at 06:43PM PST, ID: 23893160
[x]
Attachment Details

How to add an array list to a multithreaded server application

[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

9.3
The multithreaded server needs to include and arrayList to store clients threads.   Im not quite sure were to add the arrayList code:
while(true)
arrayListOfRunnables.add(new runnable);

   for(int i = 0; i < arrayListOfRunnables.size(); i++)
   
       arrayListOfRunnables.get(i).start()
   
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
389:
390:
391:
392:
393:
394:
395:
396:
397:
398:
399:
400:
401:
402:
403:
404:
405:
406:
407:
408:
409:
410:
411:
412:
413:
414:
415:
416:
417:
418:
419:
420:
421:
422:
423:
424:
425:
426:
427:
428:
429:
430:
431:
432:
433:
434:
435:
436:
437:
438:
439:
440:
441:
442:
443:
444:
445:
446:
447:
448:
449:
450:
451:
452:
453:
454:
455:
456:
457:
458:
459:
460:
461:
462:
463:
464:
465:
466:
467:
468:
469:
470:
471:
472:
473:
474:
475:
476:
477:
478:
479:
480:
481:
482:
483:
484:
485:
486:
487:
488:
489:
490:
// Fig. 24.5: MTServer.java
 
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.awt.BorderLayout;
/*import java.awt.event.ActionEvent;*/
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import java.util.ArrayList;
import javax.swing.SwingUtilities;
 
 
 
public class MTServer extends JFrame
{
   private JTextField enterField;
   private JTextArea displayArea;
   private ObjectOutputStream output;
   private ObjectInputStream input;
   private ServerSocket server;
   private Socket connection;
   private int counter = 1;
   private ArrayList runnableClients = new ArrayList();
 
   // set up GUI
   public MTServer()
   {
      super( "Server" );
      enterField = new JTextField();
      enterField.setEditable( false );
 
      /*enterField.addActionListener(
         new ActionListener()
         {
            // send message to client
            public void actionPerformed( ActionEvent event )
            {
               //serverLock.lock();
               sendData( event.getActionCommand() );
               enterField.setText( "" );
            }
         }
      ); // end ActionListener */
      
 
      add( enterField, BorderLayout.NORTH );
 
      displayArea = new JTextArea();
      add( new JScrollPane( displayArea ), BorderLayout.CENTER );
 
      setSize( 300, 150 );
      setVisible( true );
   } // end Server constructor
 
   // set up and run server
 
public void runServer()
{
 
	try
	{
		server = new ServerSocket(20000, 100);
 
		while(true)
		{
			connection = server.accept();
 
		    displayMessage( "Connection " + counter + " received from: " +
           				connection.getInetAddress().getHostName());
 
			runnableClients.add(new ClientConnection(connection, counter));
 
			int numOfClients = runnableClients.size();
 
	    	  System.out.println("the number of client threads stored is " + numOfClients + "\n");
 
	    	  for(int i = 0; i < numOfClients; i++)
	    	  {
			  	(new Thread( (ClientConnection) runnableClients.get(i) )).start();
			  }
			  counter++;
		}//end while
	}
	catch(IOException iox)
	{
	 	System.err.println("IOException in runServer");
		 iox.printStackTrace();
	}
	catch(Exception x)
	{
		System.err.println("Error in runServer()");
		x.printStackTrace();
	}
}//end runServer
 
 
 
 
/**  ClientConnecrtion run  **********************************************************************************/
 
   private class ClientConnection implements Runnable
   {
 
      private Socket sockClientConn = new Socket();
      private int clientNum;
      private ObjectOutputStream clientConnOut;
      private ObjectInputStream clientConnIn;
 
      public ClientConnection(Socket s, int cNum)
      {
		  sockClientConn = s;
		  clientNum = clientNum;
          try
          {
			  clientConnOut = new ObjectOutputStream(sockClientConn.getOutputStream());
			  clientConnOut.flush();
		  }
		  catch(IOException iox)
		  {
			  iox.printStackTrace();
		  }
 
	  }
 
	public void run()
      {
 
		System.out.println("new client thread running.");
 
		try
      	{
 
            try
            {
            	clientConnIn = new ObjectInputStream(sockClientConn.getInputStream());
            	processConnection();
            }
            catch ( EOFException eofException )
            {
               displayMessage( "\nServer terminated connection" );
            }
            finally
            {
               closeConnection();
               counter++;
          	}
 
      }
      catch ( IOException ioException )
      {
         ioException.printStackTrace();
      }
   } //end run
 
/** processConnection  *********************************************************************/
 
  private void processConnection() throws IOException, EOFException
     {
        System.out.println("entered processConnection");
        String message = "Connection successful";
        sendData( message );
 
 
        setTextFieldEditable( true );
 
  	  do
  		   {
  			   try{
  				   message = (String) clientConnIn.readObject();
  				  }
  				  catch(IOException iox)
  				  {
  					  iox.printStackTrace(System.err);
  					  System.err.println("An Error has occured client handler run()");
  				  }
  				  catch(Exception x)
  				  {
  					  System.err.println("ERROR");
  				  }
  		   }while(!message.equals("SERVER>>> TERMINATE"));
 
  		    System.out.println("leaving process connection\n");
 
 
     } // end method processConnection
 
//** close connections ****************************************************************/
 
 
	    private void closeConnection()
	    {
	       displayMessage( "\nTerminating connection\n" );
	       setTextFieldEditable( false );
 
	       try
	       {
	          clientConnOut.close();
	          clientConnIn.close();
	          connection.close();
	       }
	       catch ( IOException ioException )
	       {
	          System.err.println("Error closing connection.");
	          ioException.printStackTrace();
	       }
	    } // end method closeConnection
 
	    // send message to client
/** sendData  **************************************************************************/
 
		private void sendData( String message )
			    {
			       try // send object to client
			       {
			          clientConnOut.writeObject( "SERVER>>> " + message );
			          clientConnOut.flush();
			          displayMessage( "\nSERVER>>> " + message );
			       }
			       catch ( IOException ioException )
			       {
			          displayArea.append( "\nError writing object" );
			       }
			    } // end method sendData
  }//end clientConnection
 
private void displayMessage( final String messageToDisplay )
   {
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run() // updates displayArea
            {
               displayArea.append( messageToDisplay );
            } // end method run
         } // end anonymous inner class
      ); // end call to SwingUtilities.invokeLater
   } // end method displayMessage
 
   // manipulates enterField in the event-dispatch thread
   private void setTextFieldEditable( final boolean editable )
   {
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run() // sets enterField's editability
            {
               enterField.setEditable( editable );
            }
         }
      );
   }
 
 
}//end MTServer
 
import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
 
public class Client extends JFrame
{
   private JTextField enterField; 
   private JTextArea displayArea; 
   private ObjectOutputStream output; 
   private ObjectInputStream input; 
   private String message = ""; 
   private String chatServer; 
   private Socket client; 
 
   public Client( String host )
   {
      super( "Client" );
 
      chatServer = host; // set server to which this client connects
 
      enterField = new JTextField(); // create enterField
      enterField.setEditable( false );
      enterField.addActionListener(
         new ActionListener()
         {
            // send message to server
            public void actionPerformed( ActionEvent event )
            {
               sendData( event.getActionCommand() );
               enterField.setText( "" );
            } // end method actionPerformed
         } // end anonymous inner class
      ); // end call to addActionListener
 
      add( enterField, BorderLayout.NORTH );
 
      displayArea = new JTextArea(); 
      add( new JScrollPane( displayArea ), BorderLayout.CENTER );
 
      setSize( 300, 150 ); 
      setVisible( true ); 
   } // end Client constructor
 
   // connect to server and process messages from server
   public void runClient()
   {
      try // connect to server, get streams, process connection
      {
         connectToServer(); // create a Socket to make connection
         getStreams(); // get the input and output streams
         processConnection(); // process connection
      } // end try
      catch ( EOFException eofException )
      {
         displayMessage( "\nClient terminated connection" );
      } // end catch
      catch ( IOException ioException )
      {
         System.err.println("\nIO Exception");
         ioException.printStackTrace();
      } // end catch
      finally
      {
         closeConnection();
      } //
   } // end method runClient
 
   // connect to server
   private void connectToServer() throws IOException
   {
      displayMessage( "Attempting connection\n" );
 
      // create Socket to make connection to server
      client = new Socket( InetAddress.getByName( chatServer ), 20000 );
 
 
      displayMessage( "Connected to: " +
         client.getInetAddress().getHostName() );
   } // end method connectToServer
 
   // get streams to send and receive data
   private void getStreams() throws IOException
   {
      // set up output stream for objects
      output = new ObjectOutputStream( client.getOutputStream() );
      output.flush(); // flush output buffer to send header information
 
      // set up input stream for objects
      input = new ObjectInputStream( client.getInputStream() );
 
      displayMessage( "\nGot I/O streams\n" );
   } // end method getStreams
 
   // process connection with server
   private void processConnection() throws IOException
   {
      // enable enterField so client user can send messages
      setTextFieldEditable( true );
 
      do
      {
         try
         {
            message = ( String ) input.readObject();
            displayMessage( "\n" + message );
         }
         catch ( ClassNotFoundException classNotFoundException )
         {
            displayMessage( "\nUnknown object type received" );
         }
         catch(Exception x)
         {
			 x.printStackTrace(System.err);
		 }
 
      } while ( !message.equals( "SERVER>>> TERMINATE" ) );
   } // end method processConnection
 
   // close streams and socket
   private void closeConnection()
   {
      displayMessage( "\nClosing connection" );
      setTextFieldEditable( false );
      try
      {
         output.close(); // close output stream
         input.close(); // close input stream
         client.close(); // close socket
      }
      catch ( IOException ioException )
      {
         ioException.printStackTrace();
      }
   } // end method closeConnection
 
   // send message to server
 
/** sendData  *******************************************************************************/
 
private void sendData( String message )
   {
      try
      {
         output.writeObject( "CLIENT>>> " + message );
         output.flush(); // flush data to output
         displayMessage( "\nCLIENT>>> " + message );
      }
      catch ( IOException ioException )
      {
         displayArea.append( "\nError writing object" );
      }
   } // end method sendData
 
   // manipulates displayArea in the event-dispatch thread
 
   /** displayMessage  ***********************************************************************/
 
   private void displayMessage( final String messageToDisplay )
   {
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run() // updates displayArea
            {
               displayArea.append( messageToDisplay );
            }
         }
      ); // end call to SwingUtilities.invokeLater
   } // end method displayMessage
 
   // manipulates enterField in the event-dispatch thread
   private void setTextFieldEditable( final boolean editable )
   {
      SwingUtilities.invokeLater(
         new Runnable()
         {
            public void run()
            {
               enterField.setEditable( editable );
            }
         }
      ); // end call to SwingUtilities.invokeLater
   }
} // end class Client
 
 
import javax.swing.JFrame;
 
public class MTServerTest
{
 
   public static void main( String args[] )
   {
      MTServer application = new MTServer(); // create server
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      application.runServer();
      // run server application
   } // end main
} // end class ServerTest
 
 
import javax.swing.JFrame;
 
public class ClientTest 
{
   public static void main( String args[] )
   {
      Client application; // declare client application
 
      // if no command line args
      if ( args.length == 0 )
         application = new Client( "127.0.0.1" ); // connect to localhost
      else
         application = new Client( args[ 0 ] ); // use args to connect
 
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      application.runClient(); // run client application
      {
 
 
 
Accepted Solution by Ajar:

All comments and solutions are available to Premium Service Members only. Start your 7-day free trial to view the solution to this question.

Already a member? Login to view this solution.

 
 
Assisted Solution by rbrindl:

All comments and solutions are available to Premium Service Members only. Start your 7-day free trial to view the solution to this question.

Already a member? Login to view this solution.

 
 
20081119-EE-VQP-46 - Hierarchy / EE_QW_2_20070628