Gabriel Esteban
Gabriel Esteban

Reputation: 762

Reading data from a Socket in android

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.

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 this answer. Finally, I do what I want with the data that came by the socket.

I don't know how much data will be sended by the server. And it would be in json, but this doesn't matter.

Here my 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();
}

Upvotes: 1

Views: 2505

Answers (1)

McNinja
McNinja

Reputation: 790

Ever look at square's OKHttp or Retrofit?

http://square.github.io/okhttp/#examples

&

http://square.github.io/retrofit/

Seems easier than sockets. Do you really need sockets?

Upvotes: 1

Related Questions