How to read socket input stream in Android

     can anybody tell me how to read socket input stream. Here is my code.

if (!serverIpAddress.equals(""))
        {
            try
            {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                Log.i("ClientActivity", "Connecting...");
                Socket socket = new Socket(serverAddr, 5777);

                try {
                    Log.i("ClientActivity", "Sending command.");
                    PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                            .getOutputStream())), true);
                    // where you issue the commands
                    out.println("<maplist />");
                    Log.i("ClientActivity", "Sent.");

                    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));                     
                    buffer = new StringBuilder();

                    new Thread(new Runnable() {

                        @Override
                        public void run() {

                            try 
                            {
                                buffer.append(input.readLine());
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }).start();    
                    this.WriteXMLResponse(buffer.toString());

                } catch (Exception e) {
                    Log.e("ClientActivity", "S: Error", e);
                }

An exception is thrown in my code and in the startup method where I read the input stream. which says java.net.socketException: invalid file number.

and if I use while loop, my application freezes. Any suggestion will be appetizing. thank

+3
source share
1 answer

It's a little hard to say what happens without seeing more of your code, but here's my conclusion about what happens here (I made quite a few sockets in Android applications):

Socket BufferedReader , , , . , , , , (, Socket BufferedReader)! , Socket, . , , , readLine() , , , (fileno, unix-wise) "", .

, , while , , , Socket , , , .

- , .

, , - , , .

+7

Source: https://habr.com/ru/post/1782547/


All Articles