Android 侦听来自服务器套接字的消息 [英] Android listen for messages from server socket

查看:48
本文介绍了Android 侦听来自服务器套接字的消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通过套接字与本地服务器通信的 android 应用程序.通信使用 JSON 以字符串形式传递简单的命令和数据.客户端应该不断地监听来自服务器的传入消息,并在接收到新数据时更新用户界面.

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

        }

    }

推荐答案

您可以在您的 Service 中创建一个线程来监听服务器.第二个线程用于发送命令.然后对于您的服务,您应该创建一个带有处理程序的主线程.此处理程序将处理来自这两个线程的消息.

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.

这篇关于Android 侦听来自服务器套接字的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆