Note that there are some explanatory texts on larger screens.

plurals
  1. POReading data from a Socket in android
    text
    copied!<p>I'm getting mad trying to read data from a socket. I tried all and all, I think that my code should work but didn't.</p> <p>My intention is to only run the following method on the onCreate. First I create a Thread to run all the things that are related to the network. Then, I create the scoket object and I read the inputstream of the socket. In this moment, in an infinit loop, I read the inputstream using readLine as explained saw on <a href="https://stackoverflow.com/a/2549222/1382141">this answer</a>. Finally, I do what I want with the data that came by the socket.</p> <p>I don't know how much data will be sended by the server. And it would be in json, but this doesn't matter.</p> <p>Here my code</p> <pre><code>public void receiveMsgs(){ new Thread(new Runnable(){ @Override public void run() { BufferedReader in = null; try { Log.d("NETWORK-RECEIVE", "Trying to connect to socket..."); Socket socket; InetAddress serverAddr = InetAddress.getByName(SERVER_IP); socket = new Socket(serverAddr, SERVERPORT); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); if(socket.isConnected()){ Log.d("NETWORK-RECEIVE", "The connection have been stablished"); } } catch (IOException e) { e.printStackTrace(); Log.d("NETWORK-RECEIVE", "Something goes wrong: IOException"); } while(true){ String msg = null; try { StringBuilder total = new StringBuilder(); String line; while ((line = in.readLine()) != null) { total.append(line); } msg = total.toString(); Log.d("NETWORK-RECEIVE","Message readed!:"+msg); } catch (IOException e) { e.printStackTrace(); Log.d("NETWORK-RECEIVE", "Something goes wrong: IOException"); } if(msg == null){ Log.d("NETWORK-RECEIVE", "Message is null"); break; } else{ //Do what I want Log.d("NETWORK-RECEIVE", "something"); } } } }).start(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload