Reputation: 1955
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 ?
Upvotes: 5
Views: 6125
Reputation: 3446
You need to separate UI threads from your own network service threads. accept() is blocking (obviously) and it freezes your application until you get a new client, and freezes again waiting for more clients.
Upvotes: 5
Reputation: 52185
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.
Upvotes: 8
Reputation: 18998
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!
Upvotes: 7