Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android listen for messages from server socket

I am trying to create an android app that communicates with a local server through a socket. The communication passes simple commands and data in strings using JSON. The client should constantly listen to incoming messages from the server and update the user interface when new data is received.

So i have created a network service which is a bound service running in the background. From my activity i bind to the service and receives an instance of the service object. The service object contains instance methods which allow me to send commands to the server.

My problem is, how do i enable my service to constantly listen for messages from the server without blocking the possibility to send messages to the server?

private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;

private Listener listener;

private String host = "10.0.1.4";
private int port = 3000;

public NetworkService() 
{
    try {

        if (socket == null)
        {
        socket = new Socket(this.host, this.port);
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }

        if(listener == null)
        {
            listener = new Listener();
            Thread thread = new Thread(listener);
            thread.start();
        }

        } catch (Exception e) {
            // ...
        }
    }
}

public class Listener implements Runnable
{

    @Override
    public void run() {

        try {
            String line = null;

            while((line = in.readLine()) != null)
                {
                // Do something. Never gets here

                }
            } catch (Exception e) {
                // ...
            }

        }

    }
like image 795
Kasper Gadensgaard Avatar asked Feb 13 '12 10:02

Kasper Gadensgaard


1 Answers

You can create in your Service one thread for listening to the server. The second thread is for sending commands. Then for your service you should create a main thread with handler in it. This handler will process messages from this two threads.

like image 168
Yury Avatar answered Oct 13 '22 14:10

Yury