Android ServerSocket EADDRINUSE

I have a problem with a TCP server on Android. The server has to manage multiple incoming connections, at the moment from the same user. I got the following errors:

02-06 17:37:44.800: W/System.err(9859): java.net.BindException: bind failed: EADDRINUSE (Address already in use)
02-06 17:37:44.800: W/System.err(9859):     at libcore.io.IoBridge.bind(IoBridge.java:89)
02-06 17:37:44.800: W/System.err(9859):     at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:150)
02-06 17:37:44.800: W/System.err(9859):     at java.net.ServerSocket.bind(ServerSocket.java:318)
02-06 17:37:44.800: W/System.err(9859):     at java.net.ServerSocket.bind(ServerSocket.java:281)
02-06 17:37:44.800: W/System.err(9859):     at sample.services.TCPService$1.run(TCPService.java:84)
02-06 17:37:44.804: W/System.err(9859): Caused by: libcore.io.ErrnoException: bind failed: EADDRINUSE (Address already in use)
02-06 17:37:44.804: W/System.err(9859):     at libcore.io.Posix.bind(Native Method)
02-06 17:37:44.804: W/System.err(9859):     at libcore.io.ForwardingOs.bind(ForwardingOs.java:39)
02-06 17:37:44.804: W/System.err(9859):     at libcore.io.IoBridge.bind(IoBridge.java:87)
02-06 17:37:44.804: W/System.err(9859):     ... 4 more

      

I add setReuseAddress(true)

but nothing has changed. The code I am using is as follows. Where is the mistake? Thanks to

public void onStart(Intent intent, int startid) {
    t = new Thread(){
         public void run() {
             try {
                Log.d("TCP", "Server: Creating server.");
                ServerSocket ss = new ServerSocket();
                ss.setReuseAddress(true);
                ss.bind(new InetSocketAddress(TCPPORT));
                while(true) {
                    //Server is waiting for client here, if needed
                    Log.d("TCP", "Server: Waiting on packet!");
                    Socket s = ss.accept();
                    BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    String msg = input.readLine();
                    ......
             }
       }
};
t.start();
}

      

+3


source to share


1 answer


I solved it! The problem was that the socket must be bound after the setReuseAddress () statement.



+3


source







All Articles