如何获得数据/从主题中的插座? [英] How to get data to/from a socket in a thread?

查看:120
本文介绍了如何获得数据/从主题中的插座?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里Android的小白。我学习最好通过观察一个功能实例的源$ C ​​$ C,但我一直无法找到自己的线程使用套接字的一个简单而完整的例子。

Android noob here. I learn the best by seeing the source code of a functional example, but I have been unable to find a simple-but-complete example of using a socket in its own thread.

我有一个需要与Internet通信的机器人服务。我想打开连接到因特网上的服务器的TCP套接字。的服务需要的数据发送到互联网上,并且数据从网回来将需要去的服务。由于该服务是做其他事情还有,插座连接需要住在自己的线程。

I have an Android service that needs to communicate with the Internet. I want to open a TCP socket that connects to a server on the Internet. The service needs to send data to the Internet, and data coming back from the net will need to go to the service. Since the service is doing other things as well, the socket connection needs to live in its own thread.

任何想法,我能找到一个插座的例子在一个线程从套接字通信/?

Any idea where I could find an example of a socket in a thread with communication to/from the socket?

感谢

推荐答案

您只需创建一个异步任务通信的背景,然后根据需要更新UI线程。这里是后台线程从一个插座获得的信息和与字节数更新文本视图它接收机

You simply need to create an async task that communicates in the background and then updates the UI thread as needed. Here is the background thread to get information from a socket and update a text view with the number of bytes it receivers

  public class InternetTask extends AsyncTask<Void, Integer, Void> {

    private WeakReference<TextView> mUpdateView;

    public LoginTask(TextView view) {
        this.mUpdateView = new WeakReference<TextView>(view);
    }

    @Override
    protected Void doInBackground() {

        try {
            Socket socket = new Socket("127.0.0.1", 80);
                    InputStream is = socket.getInputStream();

                    byte[] buffer = new byte[25];
                    int read = is.read(buffer);
                    while(read != -1){
                         publishProgress(read);
                         read = is.read(buffer);
                    }

                    is.close();
                    socket.close();



        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        if(mUpdateView.get() != null && values.length > 0){
                     mUpdateView.get().setText(values[0].toString());
                }
    }

}

这里是你会怎么踢那个线程关闭

And here is how you would kick that thread off

public class TestTab extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.someLayout);

            TextView textView = (TextView)findViewById(R.id.someid);
            InternetTask task = new InternetTask(textView);
            task.execute();

    }
}

这篇关于如何获得数据/从主题中的插座?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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