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

すべてのクラスを別のスレッドで実行するだけです。では、スレッドを使用するようにクラスを変換するにはどうすればよいでしょうか。それはあなたが実際に確信していない部分だと思います。ただし、非常に簡単です...次のようにスレッド内からクラスを使用するのと同じくらい簡単です。

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

ブロックする可能性のあるものはすべて、別のスレッドで実行する必要があります。それは、データの送信、データの受信、または接続の試みです。サーバーでは、accept が含まれます。

于 2013-02-11T19:44:53.387 に答える
0

UI スレッドをブロックするため、 AsynTaskなどのバックグラウンド スレッドで実行するすべてのネットワーク (送受信) 。Networkクラスextends AsyncTaskを作成し、ドキュメントに示されている必要なメソッドを実装します。

ですべてのバックグラウンド タスクを実行してdoInBackground()から、で結果を操作しますonPostExecute()

于 2013-02-11T19:47:40.347 に答える