开发者

How to receive response all the time from server by tcp on android

I have a small开发者_如何学Go programme which can send request and receive response.

 but1.setOnClickListener(new Button.OnClickListener()
        {
            public void onClick(View v) {
                Socket socket=null;
                String mesg=edit1.getText().toString()+"\r\n";
            try {
                socket=new Socket("169.243.146.84",30000);
                //send information to server
                PrintWriter out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                out.println(mesg);
                //receive information from server
                BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String mstr=br.readLine();
            if(mstr!=null)
            {
                text1.setText(mstr);
            }else
            {
                text1.setText("error");
            }

            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }catch(Exception e)
            {
                Log.e(DEBUG_TAG,e.toString());
            }
}
});

When I click the button, it will send and receive. But I want it to receive response all the time. Like the server will send different information every 10 seconds. So I can use append() to setText.

Could someone tell me how to do that?

Thanks!


you need to start a thread and loop into it until the socket is closed (or the server sends a stop message).

new Thread(new Runnable() {
    public void run() {
        while (true) {
            String mstr=br.readLine();
            if (mstr == null) {
                break; // socket closed
            }
            if (mstr.equals("%QUIT%")) {
                break; // protocol specific end message
            }
            // do whatever you like with mstr
            // ....
        }
    }
}

You need to add a bit of exception handling, and it will be fine. The server will be able to talk to the client, whenever he likes, and without being asked anything.

The only downside is that you need to maintain the socket connection during the messages exchanges. Now why do that ? Well, imagine you have an appointment in 1 hour. Do you prefer to look at your watch every 10 seconds, or set up an alarm on your watch that will inform you in 1 hour?


Use a TimerTask that wakes up every 10 sec and tries to read the information if present or even every sec. This is not recommended though you should look at C2DM for push notification.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜