简体   繁体   中英

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.

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. I originally followed this tutorial: NETWORKING TUTORIAL and i didnt quite under stand their tcp class where they have run methods.

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).

On Android it is important to use threading in order to avoid blocking the 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 . So the question here is: " How the heck should I update my UI to reflect changes on my worker thread? ".

There are quite few ways... on of the most populars is the AsyncTask class. It basically allows you to run background threads and offer ways to update the UI in a safe way. They are useful if you know the Activity won't be finished while the AsyncTask is running.

If you are running more long-term tasks, you better use a 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. Have your Network class extends AsyncTask and implement the required methods shown in the docs.

Do all of your background tasks in doInBackground() then manipulate your results in onPostExecute()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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