简体   繁体   English

java.net.BindException:绑定失败:EADDRINUSE

[英]java.net.BindException: bind failed: EADDRINUSE

I am new to android and i am trying to create a server socket . 我是android新手,正在尝试创建服务器套接字。 the code follows. 代码如下。

i am getting the warning continuously . 我不断收到警告。 can it be fixed ? 可以解决吗? can i ignore it? 我可以忽略它吗?

03-28 15:47:34.460: W/System.err(3185): java.net.BindException: bind failed: EADDRINUSE (Address already in use)

03-28 15:47:34.460: W/System.err(3185):     at libcore.io.IoBridge.bind(IoBridge.java:89)

03-28 15:47:34.460: W/System.err(3185):     at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:150)

03-28 15:47:34.460: W/System.err(3185):     at java.net.ServerSocket.<init>(ServerSocket.java:100)

03-28 15:47:34.470: W/System.err(3185):     at java.net.ServerSocket.<init>(ServerSocket.java:69)

03-28 15:47:34.470: W/System.err(3185):     at <path>$server.run(<filename>.java:302)

03-28 15:47:34.470: W/System.err(3185):     at java.lang.Thread.run(Thread.java:856)
03-28 15:47:34.470: W/System.err(3185): Caused by: libcore.io.ErrnoException: bind failed: EADDRINUSE (Address already in use)

03-28 15:47:34.470: W/System.err(3185):     at libcore.io.Posix.bind(Native Method)
03-28 15:47:34.470: W/System.err(3185):     at ibcore.io.ForwardingOs.bind(ForwardingOs.java:39)
03-28 15:47:34.470: W/System.err(3185):     at libcore.io.IoBridge.bind(IoBridge.java:87)
03-28 15:47:34.470: W/System.err(3185):     ... 5 more

03-28 15:47:34.470: W/System.err(3185): java.lang.NullPointerException
03-28 15:47:34.490: W/System.err(3185):     at <path>Provider$server.run(<filename>.java:315)

03-28 15:47:34.490: W/System.err(3185):     at java.lang.Thread.run(Thread.java:856)

Code: 码:

class server implements Runnable {

        public void run() {


        ServerSocket serverSocket = null;
            try {
                serverSocket = new ServerSocket(10000);
            } catch (IOException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }
            //  Log.d("Recieving ", "Server Socket Created");


            try {
                while(true) {
                    // Blocks until a connection occurs:
                    try {

                Socket client = serverSocket.accept();
                        //Log.d("Recieving ", "Client request accepted");
                        str_proc tk = new str_proc(client);
                        tk.start();

                    } catch (IOException e1) {

                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                        Log.d("Recieving ", "Problem creating socket for listening");

                    }
                }//while true loop ends

            }catch (Exception e){
                e.printStackTrace();
            }
        }
}

Your exception handling is up the pole. 您的异常处理至关重要。

The catch after the creation of the ServerSocket shouldn't be there at all: it should be after the code that uses the ServerSocket , in which case it could be combined with the existing second catch. 创建ServerSocket之后的渔获根本不应该存在:它应该在使用ServerSocket的代码之后,在这种情况下,可以与现有的第二渔获结合。 Code that relies on the success of code in a prior try block should be inside that try block. 依赖于先前try块中的代码成功的代码应位于该try块内。

However, the only way you can be getting that error continuously is if you are starting the thread continuously, which doesn't make sense anyway as you can only have one listener at any given TCP port. 但是,连续出现该错误的唯一方法是连续启动线程,但这毫无意义,因为在任何给定的TCP端口上只能有一个侦听器。

So investigate why you are starting the thread over and over again, and stop it, 因此,调查一下为什么要一遍又一遍地启动线程并停止它,

You can call close() from another thread, and the accept() call will throw a SocketException. 您可以从另一个线程调用close() ,然后accept()调用将引发SocketException。 In this way in the next call of ServerSocket constructor you won't get " java.net.BindException : bind failed: EADDRINUSE". 这样,在ServerSocket构造函数的下一次调用中,您将不会得到“ java.net.BindException :绑定失败:EADDRINUSE”。

activity_main.xml activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"`enter code here`
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="project.vasile.emanuel.gresanu.test_server_socket.MainActivity">

<Button
    android:id="@+id/btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Click"/>
</RelativeLayout>

MainActivity 主要活动

public class MainActivity extends AppCompatActivity {

    private static final String TAG=MainActivity.class.getSimpleName();
    private static boolean isClick;
    private My_Server My_Server;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn=(Button) findViewById(R.id.btn);
        isClick=false;
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                 if(!isClick)
                 {
                     Log.i(TAG,"Initilize and Running My_Server");
                     My_Server =new My_Server();
                     if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.HONEYCOMB)
                     {
                         My_Server.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,(Void[])null);
                     }
                     else
                     {
                         My_Server.execute((Void[])null);
                     }
                     isClick=true;
                 }
                else
                 {
                    if(null!= My_Server)
                    {
                        My_Server.cancelAccept();
                        isClick=false;
                    }
                 }
            }
        });
    }
}

My_Server 我的服务器

public class My_Server extends AsyncTask<Void, Void, Void> {

    private static final String TAG = My_Server.class.getSimpleName();
    private static final int PORT = 8091;
    private static boolean isExiting;
    private ServerSocket serverSocket;

    @Override
    protected Void doInBackground(Void... params) {
        isExiting = false;
        try {
            serverSocket = new ServerSocket(PORT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Socket clientSocket=null;
        if(null!=serverSocket)
        while (!isExiting) {
            try {
                Log.i(TAG, "Waiting for a new connection");
                clientSocket=serverSocket.accept();
                Log.i(TAG, "Connction accepted");
                //Do something with the new client
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
                if(null!=this.serverSocket&& !serverSocket.isClosed()) {
                    try {
                        Log.i(TAG,"Closing Server connection");
                        this.serverSocket.close();
                    } catch (IOException e2) {
                        e2.printStackTrace();
                    }
                }
            }
        }
        try {
            Log.i(TAG,"Closing the connection");
            if(null!=serverSocket && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG,e.getMessage());
        }
        return null;
    }

    public void cancelAccept() {
        Log.i(TAG, "cancelAccept()");
        isExiting = true;
        if(null!=this.serverSocket&& !serverSocket.isClosed())
        {
            try {
                Log.i(TAG,"Closing Server connection in onCancelled");
                this.serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.gc();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决java.net.BindException:绑定失败:EADDRINUSE(地址已在使用中) - How to resolve java.net.BindException: bind failed: EADDRINUSE (Address already in use) java.net.BindException:EADDRINUSE(地址已在使用中) - java.net.BindException: EADDRINUSE (Address already in use) java.net.BindException:JVM绑定 - java.net.BindException:JVM Bind java.net.BindException:绑定失败:尝试为UDP连接创建DatagramSocket时EACCES(权限被拒绝) - java.net.BindException: bind failed: EACCES (Permission denied) when trying to create DatagramSocket for UDP connection tomcat 错误:java.net.BindException:无法分配请求的地址(绑定失败) - tomcat error: java.net.BindException: Cannot assign requested address (Bind failed) java.net.BindException:绑定失败:EADDRNOTAVAIL(无法分配请求的地址) - java.net.BindException: bind failed: EADDRNOTAVAIL (Cannot assign requested address) java.net.BindException:绑定失败:EACCES(权限被拒绝)TCP Server - java.net.BindException: bind failed: EACCES (Permission denied) TCP Server 遇到java.net.BindException:服务器客户端套接字应用程序上已在使用的地址(绑定失败) - Running into an java.net.BindException: Address already in use (Bind failed) on server- client socket app 抛出java.net.BindException的单独线程中的ServerSocket:绑定失败:Android上的EACCES(权限被拒绝) - ServerSocket in seperate thread throwing java.net.BindException: bind failed: EACCES (Permission denied) on Android java.net.BindException:已在使用的地址:无法绑定 - java.net.BindException: Address already in use: Cannot bind
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM