TAGS :Viewed: 8 - Published at: a few seconds ago

[ FXML controller and Threads ]

So, I'm coding a college assignment and I got stuck in a part where I have to build a Thread for a SocketServer which open new Threads for each client connection. Here's the java code:

This method is linked to the setOnAction of a Button:

 void openServer(){
    new ServerThread().startThread();
}

This is the method called by the method above:

public class ServerThread implements Runnable{

  private ServerSocket serv;
  @Override
  public void run(){
        try {
            serv = new ServerSocket(1234);
            while(true){
                Socket sc = serv.accept();
                System.out.println("Someone connected!");
                Thread t = new Thread(new ClientThread(sc));
                t.start();
            }
        } catch (IOException e) {
            System.out.println("Erro no servidor");
        }
   }

   void startThread(){
       Thread t = new Thread(new ServerThread());
       t.run();
   }

}

This is the thread called by the code above:

public class ClientThread implements Runnable{
    private Socket sock;

   @Override
   public void run() {
       try {
           BufferedReader in = new BufferedReader(new InputStreamReader(sock.getInputStream()));

            while(true){
                int cmd = in.read();
                if(cmd == 1){
                    //REGISTER
                } else if (cmd == 2){
                    //LOGIN
                }
            }
        } catch (IOException e) {
             System.out.println("Erro no socket");
        }

    }
    public ClientThread(Socket s){
        this.sock = s;
    }
}

The problem is: when the button is clicked, the Application just stop responding, as if the Application and the SocketServer were running at the same Thread, just want to know what is happening and a fix for it.

Answer 1


The mistake is at the startThread() method, the call for the thread should be t.start() but I wrote t.run(). Yes I was that dumb, thanks @James_D for the help in the comments.