Android listen for messages from server socket

拥有回忆 提交于 2021-02-17 20:06:46

问题


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) {
                // ...
            }

        }

    }

回答1:


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.



来源:https://stackoverflow.com/questions/9258677/android-listen-for-messages-from-server-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!