插座EADDRINUSE(地址已在使用) [英] Socket EADDRINUSE (Address already in use)

查看:251
本文介绍了插座EADDRINUSE(地址已在使用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的socket编程。

I am doing socket programming.

我从下面的链接托克参考:

I tok reference from below link:

http://examples.java$c$cgeeks.com/android/core/socket-core/android-socket-example/

下面是我的问题的细节:
我创建的Andr​​oid的lib这个ServerThread(我的项目要求)。
这是在测试程序使用。

Below is detail about my issue: I have created android lib for this ServerThread (my project requirement). and this is used in test app.

现在测试应用程序通过LIB连接到这一点,并做处理。第一次工作完全正常,但如果我关闭并重新打开它,出现异常崩溃的EADDRINUSE(地址已在使用)

Now test app connect to this through lib and do the process. first time it works perfectly fine, but if I closed and reopen it crashed with exception "EADDRINUSE (Address already in use)"

也试过serverSocket.setReuseAddress(真);这一点,但没有运气...

Also tried serverSocket.setReuseAddress(true); this but no luck...

我的code:

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作为服务器套接字关闭。
 在previous链接给通信线程是一样的。

If I call serverSocket.close() I am getting exception 2 as server socket close. Communication thread is same as given in previous link.

推荐答案

您必须调用 setReuseAddress(真)前的套接字绑定到的端口。你是后调用它,因为你传递端口的构造,这将套接字绑定立即

You have to call setReuseAddress(true) before the socket is bound to the port. You are calling it after, because you are passing the port to the constructor, which will bind the socket immediately.

试试这个:

serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SERVER_PORT)); // <-- now bind it

这篇关于插座EADDRINUSE(地址已在使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆