Search code examples
javasocketsserversocket

Java socket : how to prevent java.net.BindException


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 :)


Solution

  • 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.