JAVA - Socket.accept () freezes ui

I am trying to make a multi-threaded server / client application with java! this code is for the listen () method in a package class called 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 the method below the main Bgui class (iserver.core.ui). Bgui is a jframe that contains a text field and something else! the problem is when the executable methods accept, ui.log does not work! What is wrong here?

+4
source share
3 answers

You need to separate user interface threads from your own network service threads. accept () blocks (obviously) and freezes your application until you get a new client, and freezes again, expecting more clients.

+4
source

You will need to start your server in a separate thread, since .accept is a blocking call. You might want to do something like this:

 (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 has not been verified, but it should give you an idea of ​​what you need to do.

+7
source

Socket.accept() blocks until an incoming connection is received (see the documentation). You should not block calls from the user interface thread, otherwise it will be ... you know ... block!

+6
source

Source: https://habr.com/ru/post/1403459/


All Articles