我正在做套接字编程。我引用了以下链接:
http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/
以下是有关我的问题的详细信息。我已经为此 ServerThread 创建了 Android 库(我的项目要求),并将其用于测试应用。
现在测试应用程序通过 lib 连接到此并执行该过程。第一次它工作得很好,但如果我关闭并重新打开它会崩溃并出现异常:
"EADDRINUSE (Address already in use)"
还尝试了 serverSocket.setReuseAddress(true)
但没有成功。
我的代码:
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVER_PORT);
serverSocket.setReuseAddress(true);
} catch (IOException e) {
Log.e(TAG, "exception1= " + e.getMessage());
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
Log.d(TAG, "server Connected.......!!!!");
communicationThread = new CommunicationThread(
socket);
commThread = new Thread(communicationThread);
commThread.start();
} catch (IOException e) {
Log.e(TAG, "exception 2=" + e.getMessage());
}
}
}
如果我调用 serverSocket.close()
,我会在服务器套接字关闭时收到异常 2。通信线程与上一个链接中给出的相同。
最佳答案
在将套接字绑定(bind)到端口之前,您必须调用 setReuseAddress(true)
。您在之后调用它,因为您将端口传递给构造函数,它将立即绑定(bind)套接字。
试试这个:
serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SERVER_PORT)); // <-- now bind it
关于android - Socket EADDRINUSE(地址已被使用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24615704/