Hello! There is a Nexus 5 with Android 5.1 and there is a server on the sockets: https://gist.github.com/anonymous/5ae47fa60773dc6d023a

In another thread working with clients: https://gist.github.com/anonymous/7dffdbd4321c8cba41a3

So, when you try to send a response, an exception is thrown:

sendto failed: EBADF (Bad file number)

What is most surprising is that on Windows the similar code works correctly.

Has anyone encountered this problem?

  • Specify what you mean - "Windows similar code works correctly" - anber
  • one
    Add code to the question, information on the links may disappear (what happened with the 2 link) - DeKaNszn
  • I accidentally deleted the code from the second link, but the code in the answer is the same. - Evgeniy

1 answer 1

Correct answer. It turned out everything is simple. Do not close the BufferedReader on the 19th line. Corrected working option:

public class ServerEcho extends Thread{ private final String LOG_TAG = "ServerEcho"; private Socket socket; public ServerEcho(Socket socket) { this.socket = socket; } @Override public void run() { super.run(); try { InputStream inputStream = socket.getInputStream(); OutputStream os = socket.getOutputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream)); String answer = br.readLine(); Log.d(LOG_TAG, answer); os.write(new String("ANSWER+").getBytes()); // <- Здесь выбрасывается исключение sendto failed: EBADF (Bad file number) os.flush(); os.close(); br.close(); // < ----- Закрываем здесь! }catch (Exception e){ Log.e(LOG_TAG, "#1: "+e.getMessage()); } } } 

https://gist.github.com/anonymous/92ee967ce9030adb061a