Link to home
Start Free TrialLog in
Avatar of eire_ireland
eire_ireland

asked on

how to add a server thread

Below is code that implements a thread on a server when a client connects. Im trying to modify the code as to accept a connection from two clients and handle each connection(client) in a different thread.

//this is the actual code in the server
 serve = new ServerSocket( 5004, 1000 ) ;
   
 new ClientThread(serve.accept());

   }
   catch( IOException e )
  {
   e.printStackTrace() ;
  }

 } //end while

class ClientThread extends Thread {
   private Socket socket;
 

   public ClientThread(Socket socket) {
     this.socket = socket;
     start();
   
   }


//this is what im trying to implement, this is not part of the code in the server
thread1 = new ClientThread(serve.accept());
thread2 = new ClientThread(serve.accept());

public ClientThread(Socket socket) {
     this.socket = socket;
    System.out.println("start");
     thread1.start();
     System.out.println("stop");
     thread2.start
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

It's already doing that! Every time a client connects, a new thread is created and started.
> new ClientThread(serve.accept());

you are already creating a thread you just need to start it:

new ClientThread(serve.accept()).start();
>    System.out.println("start");
>     thread1.start();
>     System.out.println("stop");
>     thread2.start

You don't need to do that
Alternatively you could start it in the ctor:

public ClientThread(Socket socket) {
     this.socket = socket;
     start();
}

But I'd suggest starting as I posted above, allowing the main thread to control when new threads are started.
SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of eire_ireland
eire_ireland

ASKER

ya, thats where its referring to, the reason I think its only starting one thread is cos when I connect with a second client it does'nt the server does'nt output the string sent by the second client.
correction : "it does'nt" should'nt be there after client
you only need one thread.
meaning one thread per client.
> output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()), true);

no need to do that every loop, you should move that call outside the loop.
put it after where you define in.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Cheers fellas
:-)