1

I have implemented a LAN game and test on same computer by : create a class, create a server and a client in different thread in this class and connect together.

After I close two windows (client and server) and I do above step again : run java class, create a server and a client. I always meet this error : java.net.BindException (because this port has been created before and hasn't closed yet).

Every time I create server socket, in catch, I always put serverSocket.close(). but that error still met with me. Please give me some ideas to prevent this.

@ : and if we know one port has been created, can we close it, and make new ones ?

Thanks :)

0

3 Answers 3

2

Anything put in a catch block isn't run unless an Exception is caught. Instead, put the close() call in a finally block to ensure it is always run.

Sign up to request clarification or add additional context in comments.

Comments

2

You should put serverSocket.close() in your finally block and maybe wait a few seconds before trying to bind to that address again.

Comments

0

After calling close() on channel could be not enough. See explanation here: http://hea-www.harvard.edu/~fine/Tech/addrinuse.html The TCP connection could stay in CLOSE-WAIT or TIME-WAIT state. You can play with reusing the address (SO_REUSEADDR), but it didn't work for me. The best is to wait exactly the timeout which is set for CLOSE-WAIT or TIME-WAIT on network level.

Comments

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.