简体   繁体   English

与android的线程和网络

[英]Threads and networking with android

Good day, 美好的一天,

I am busy writing a networking class for an android application that is going to make use of the wireless tcp connection on the phone. 我正忙着为一个Android应用程序编写一个网络类,它将利用手机上的无线tcp连接。

This class below is what i have coded so far. 下面这个类是我到目前为止编码的。 But when coding it i forgot about the multi- threading aspect of it. 但是在编码时我忘记了它的多线程方面。

Network class: 网络课程:

// Network Class That controls all the connecting, sending of data and recieving of data over the tcp protocol
public class Network {

    // GLOBAL VARIABLE DELERATIONS
    public Socket TCPSocket;
    public OutputStream out;
    public BufferedReader in;
    public InetAddress serverAddr;
    // Servers IP address
    public String SERVERIP;
    // Servers Port no.
    public int SERVERPORT;

    BufferedReader stdIn;

    // Constructor
    public Network() {

        // Set The IP of the server
        SERVERIP = "41.134.61.227";
        // Define the port for the socket
        SERVERPORT = 8020;
        // Resolve the ip adress
        try {
            serverAddr = InetAddress.getByName(SERVERIP);
            Log.i("IP Adress: ", "Has been resolved");
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * Connect to the server socket
     * 
     * @return a boolean indicating if the connection was successful
     */
    public boolean connect() {

        // Create the Socket Connections
        try {
            Log.i("TCP is attempting to establish a connection", null);
            TCPSocket = new Socket(serverAddr, SERVERPORT);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.e("TCP Connection error :", e.toString());
            return false; // Returns if the connection was unsuccessful
        }
        Log.i("TCP Connection :", "Connected");
        return true; // Returns if the connection was successful
    }

    /**
     * Disconnect from the server socket: Method to Call once you are done with
     * the network connection, Disconnects the socket from the server
     */
    public void disconnect() {

        try {
            out.close();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } // Close the out Stream

        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // stdIn.close();
        try {
            TCPSocket.close(); // Close the TCP Socket
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Log.i("TCP Connection :", "Disconnected");
    }

    /**
     * Send: Function that will transmit data aver the tcp socket (network)
     * 
     * @param data
     *            the packet in raw data form, recieves a byte array
     * @return Returns a boolean if the transaction was successful.
     */
    // Function that will transmit the data over the tcp socket.
    public boolean send(byte[] data) {
        try {
            out.write(data); // Write the data to the outStream
            out.flush();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false; // Return false if the TCP Transmit failed or
                            // encounted an error
        }
        return false;
    }

    // Function that will return the data that has been recieved on the tcp
    // connection from the server

    /**
     * Recieve: Function that recives data from the socket.
     * 
     * @return
     */
    public byte[] recieve() {

        return null;
    }

What do i need to do to convert my class to use threads? 我需要做什么才能将我的类转换为使用线程?

Which parts of it need to run on their own thread? 它需要在自己的线程上运行哪些部分?

I would think that only the receive needs it own thread? 我认为只有接收需要它自己的线程? as the send is only run when you call it ? 因为发送只在你打电话时运行?

Sorry for the noob question but this is my 1st attempt at writing a networking app without just coping some example code from the net. 对于noob问题很抱歉,这是我第一次尝试编写网络应用程序,而不仅仅是从网上处理一些示例代码。 I originally followed this tutorial: NETWORKING TUTORIAL and i didnt quite under stand their tcp class where they have run methods. 我最初遵循本教程: NETWORKING TUTORIAL ,我没有完全站在他们运行方法的tcp类。

So to summarize my question, which particular parts, when networking need to but run on a different thread? 那么总结一下我的问题,哪些特定的部分,当网络需要但在不同的线程上运行? Thanks 谢谢

Thanks 谢谢

I'd just run all the class on a different thread. 我只是在不同的线程上运行所有类。 So... how do you convert a class to use threads? 那么......你如何转换一个类来使用线程? I think that's the part that you actually don't feel sure about. 我认为那是你实际上不确定的部分。 It's quite easy though... it can be as simple as using the class from within a Thread like this: 这很简单......它可以像在线程中使用类一样简单:

new Thread(new Runnable(){
  public void run() {
    new Network().connect();
  }
}).start();

This will run your code on a separate Thread, and you don't even have to modify the class. 这将在单独的线程上运行您的代码,您甚至不必修改类。 So... that said... let's talk about Android (that snippet of code above is pure Java, but that's only the tip of the iceberg). 所以...说...让我们谈谈Android(上面的代码片段是纯Java,但这只是冰山一角)。

On Android it is important to use threading in order to avoid blocking the UI; 在Android上,使用线程以避免阻止UI非常重要; that can be done with snippets of code like the one above, but such approach could cause some problems. 可以使用上面的代码片段来完成,但这种方法可能会导致一些问题。 So you have to learn this rule: I will not change my UI from within an external Thread . 所以你必须学习这个规则: 我不会在外部线程中更改我的UI So the question here is: " How the heck should I update my UI to reflect changes on my worker thread? ". 所以这里的问题是:“ 我应该如何更新我的UI以反映我的工作线程的变化? ”。

There are quite few ways... on of the most populars is the AsyncTask class. 有很多方法......最流行的是AsyncTask类。 It basically allows you to run background threads and offer ways to update the UI in a safe way. 它基本上允许您运行后台线程并提供以安全的方式更新UI的方法。 They are useful if you know the Activity won't be finished while the AsyncTask is running. 如果您知道在AsyncTask运行时不会完成Activity则它们非常有用。

If you are running more long-term tasks, you better use a Service . 如果您正在运行更多长期任务,则最好使用Service There are fancy ways to run background threads on a service ; 有一些奇特的方法可以在服务上运行后台线程 ; but you can also do it by yourself. 但你也可以自己做。

Anything that could block should be run on a different thread. 任何可以阻止的东西都应该在不同的线程上运行。 That would be any attempt to send data, receive data, or connect. 这将是发送数据,接收数据或连接的任何尝试。 On a server it would include accept. 在服务器上它将包括接受。

All of your networking (receiving and sending) you want to run on a background thread such as in an AsynTask as it will block your UI thread. 你想要在后台线程上运行的所有网络(接收和发送),例如在AsynTask中 ,因为它将阻止你的UI线程。 Have your Network class extends AsyncTask and implement the required methods shown in the docs. 让您的Networkextends AsyncTask并实现文档中显示的所需方法。

Do all of your background tasks in doInBackground() then manipulate your results in onPostExecute() 是否所有的在你的后台任务doInBackground()然后操纵在你的结果onPostExecute()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM