0

再会,

我正忙着为一个将要使用手机上的无线 tcp 连接的 android 应用程序编写一个网络类。

下面的这个类是我迄今为止编写的。但是在编码时我忘记了它的多线程方面。

网络类:

// 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;
    }

我需要做什么才能将我的类转换为使用线程?

它的哪些部分需要在自己的线程上运行?

我认为只有接收需要它自己的线程?因为发送仅在您调用它时运行?

抱歉这个菜鸟问题,但这是我第一次尝试编写网络应用程序,而不仅仅是从网络上处理一些示例代码。我最初遵循本教程:NETWORKING TUTORIAL,但我不太了解他们运行方法的 tcp 类。

所以总结一下我的问题,当网络需要但在不同的线程上运行时,哪些特定部分?谢谢

谢谢

4

3 回答 3

2

我只是在不同的线程上运行所有课程。那么......你如何将一个类转换为使用线程?我认为这是您实际上不确定的部分。不过这很容易......它可以像在这样的 Thread 中使用类一样简单:

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

这将在单独的线程上运行您的代码,您甚至不必修改该类。所以......也就是说......让我们谈谈Android(上面的代码片段是纯Java,但这只是冰山一角)。

在 Android 上,使用线程以避免阻塞 UI 很重要;这可以通过上面的代码片段来完成,但是这种方法可能会导致一些问题。所以你必须学习这条规则:我不会从外部 Thread 中更改我的 UI。所以这里的问题是:“我到底应该如何更新我的 UI 以反映我的工作线程上的变化? ”。

有很多方法......最受欢迎的是AsyncTask类。它基本上允许您运行后台线程并提供以安全方式更新 UI 的方法。Activity如果您知道在运行时不会完成,它们会很有用AsyncTask

如果您正在运行更多长期任务,则最好使用Service. 在服务上运行后台线程有很多奇特的方法;但你也可以自己做。

于 2013-02-11T19:46:59.270 回答
0

任何可能阻塞的东西都应该在不同的线程上运行。这将是发送数据、接收数据或连接的任何尝试。在服务器上它将包括接受。

于 2013-02-11T19:44:53.387 回答
0

您希望在后台线程(例如在AsynTask中)上运行的所有网络(接收和发送),因为它会阻塞您的 UI 线程。让您的Network课程extends AsyncTask并实现文档中显示的所需方法。

完成所有后台任务,doInBackground()然后操纵结果onPostExecute()

于 2013-02-11T19:47:40.347 回答