因为tcp client端要用到一个固定的端口 TERMINAL_CLIENT_PORT ,用以下代码,老是出现EADDRINUSE (Address already in use)的错误
sk = new Socket(packet.getAddress(), testServicePort, InetAddress.getByName(getLocalIpAddress()), TERMINAL_CLIENT_PORT);
sk.setReuseAddress(true);
上网查了一个,说只要 调用sk.setReuseAddress(true); 就可以了,但是显然没有起到作用。
经过很多失败后,用以下的代码,终于 解决问题
sk = new Socket();
sk.setReuseAddress(true);
InetSocketAddress socketAddress = new InetSocketAddress(InetAddress.getByName(getLocalIpAddress()), TERMINAL_CLIENT_PORT);sk.bind(socketAddress);
sk.connect(new InetSocketAddress(packet.getAddress(), testServicePort));
原因是什么,就不用多说了吧。