I am sending a single message to a TCP server and after running it once I get java.net.BindException: Address already in use
errors when I try to run it again. I figured that the socket would be unbound; I can't find anything specifically saying that it does in the documentation, though. How do I free up the port, am I not ending the transaction properly here? Here is my client:
public class TcpPingClient {
public static void main(String[] args) throws Exception {
Socket tcpSocket = new Socket();
tcpSocket.bind(new InetSocketAddress("192.168.1.2", 45030));
tcpSocket.connect(new InetSocketAddress("192.168.1.2", 1211));
DataOutputStream out = new DataOutputStream(tcpSocket.getOutputStream());
out.writeBytes("oh hey\n");
tcpSocket.close();
}
}
It is unbound, but waiting for timeout in case the other end need some data buffered on the senders end. If you want to re-use a port without waiting for this to happen you can use
socket.setReuseAddress(true);
This must be set before you attempt to bind.
In short, this is how TCP is implemented, not a feature of Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With