Search code examples
javasocketsjavafx-8serversocket

Socket communication between javafx


Hi i'm having a trouble using socket with javafx application.

client code

@FXML
    private void onSetupGameClick() {
        try{    
            Socket s=new Socket("localhost",6666);

            DataOutputStream dout=new DataOutputStream(s.getOutputStream());

            dout.writeUTF("Hello Server");
            dout.flush();

            dout.close();
            s.close();

            }catch(Exception e){
                System.out.println(e);
                }
    }

The above code start the socket server when button clicked.

server code

@Component
public class WelcomeController implements BootInitializable {

    @Override
    public void initialize(URL arg0, ResourceBundle arg1) {

        try {
            ServerSocket ss=new ServerSocket(6666);
            Socket s=ss.accept();//establishes connection 

            DataInputStream dis=new DataInputStream(s.getInputStream());

            String  str=(String)dis.readUTF();
            System.out.println("message= "+str);
            lblGame.setText(str);

            ss.close();
            System.out.println("Connection created");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Above code will create client on other javafx application. The problem is ,when the client application started it will not show the UI, i think it will wait for server to connect. When the server application started as soon the client ui will showed up.How to solve this issue.


Solution

  • JavaFX has it's own thread that it runs on, and handles the gui. When you perform blocking tasks on that thread it will block the gui. One thing you can do, is in your button handler, fire off a new thread.

    new Thread(()->{onSetupGameClick();}).start();
    

    I hope you can see this is a bad design because you can accumulate multiple started threads.

    Maybe check out something like this JavaFX SwingWorker Equivalent? for a more complete example.