1
while (true) {

    ServerSocket myServerSocket = new ServerSocket(9999);
    Socket skt = myServerSocket.accept();

    Handling obj = new Handling();
    obj.handle(skt);

}

When i first try this it works fine and accepts the Socket but then when it loops back it says the address is in use. How do I fix this?

1 Answer 1

4

Don't create a new ServerSocket in the loop - you only need to accept in the loop:

ServerSocket myServerSocket = new ServerSocket(9999);
while (true) {
    Socket skt = myServerSocket.accept();
    Handling obj = new Handling();
    obj.handle(skt);
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is the right solution, however the reason the OP's code didn't work is that it didn't close() the server socket before creating it again. This would have worked also but is not good practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.