Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JAVA - Socket.accept() freezes ui

I'm trying to make a multithreaded server/client app with java ! this code is for listen() method in a class of a package that named Bsocket (iserver.core.socket) :

 try {
     serverSocket = new ServerSocket(port);
 }catch(IOException e ){
     ui.log(e.toString());//*
 }
while (true){
    try{
        clienSocket = serverSocket.accept();
        ui.log("Incomming Connection.");//*
        new connectionHandler(clienSocket, ui);
    }catch(IOException e ){
        ui.log(e.toString());
    }
}

ui.log("Incomming Connection."); is a method in below of main class of Bgui (iserver.core.ui).Bgui is a jframe that contain a textarea and something else ! the problem is when the accept methods executed , the ui.log did not works ! whats wrong here ?

like image 704
bizzr3 Avatar asked Mar 26 '12 12:03

bizzr3


2 Answers

You will need to launch your server on a seperate thread since .accept is a blocking call. You might want to do something like so:

(new Runnable() {
    @Override
    public void run()
    {
         try {
              serverSocket = new ServerSocket(port);
          }catch(IOException e ){
              ui.log(e.toString());//*
          }
         while (true){
             try{
                 clienSocket = serverSocket.accept();
                 ui.log("Incomming Connection.");//*
                 new connectionHandler(clienSocket, ui);
             }catch(IOException e ){
                 ui.log(e.toString());
             }
         }
    }
}).start();

NOTE: This code is not tested, but it should give you an idea of what you need to do.

like image 62
npinti Avatar answered Oct 11 '22 15:10

npinti


Socket.accept() blocks until there's an incoming connection to receive (see the documentation). You shouldn't be making any blocking calls from your UI thread - otherwise it will... you know... block!

like image 37
dty Avatar answered Oct 11 '22 14:10

dty