TCP客户端:从TCP连接接收字节 - Java,Android

时间:2016-10-03 16:46:05

标签: java android tcp client bufferedinputstream

我正在开发一个从服务器接收一些数据的Android应用程序。 我将本教程用于TCP客户端:TCP Tutorial

与教程不同,我需要将数据作为 byte [] 而不是字符串,但我无法弄清楚如何执行此操作。

我的TCP客户端:

Coredata

主要活动:

public class TCPClient {

private OnMessageReceived mMessageListener = null;
private BufferedInputStream input;
private byte[] serverMessage; // message received from server

private boolean mRun = false;

/**
 *  Constructor:
 *  OnMessagedReceived listens for the messages received from server.
 */
public TCPClient(OnMessageReceived listener) {
    mMessageListener = listener;
}

/**
 * Connection thread
 */
public void run() {
    mRun = true;

    try {
        // Server address:
        InetAddress serverAddr = InetAddress.getByName(10.0.0.170);

        Log.e("TCP Client", "C: Connecting...");

        // Connection socket:
        Socket socket = new Socket(serverAddr, 4848);

        try {
            // Input stream from server:
            input = new BufferedInputStream(socket.getInputStream());

            // Listen for messages from server:
            while (mRun) {
                int bytesRead = input.read();
                serverMessage = new byte[bytesRead];

                if (serverMessage != null && mMessageListener != null) {
                    mMessageListener.messageReceived(serverMessage);
                }

                serverMessage = null; // reset serverMessage
            }
        } catch (Exception e) {
            Log.e("TCP", "S: Error", e);
        } finally {
            socket.close();
        }
    } catch (Exception e) {
        Log.e("TCP", "C: Error", e);
    }
}

public void stopClient(){
    mRun = false;
}

/**
 * The method messageReceived(byte[] message) must be implemented in the
 * MainActivity class at on asynckTask doInBackground
 */
public interface OnMessageReceived {
    public void messageReceived(byte[] message);
}

}

Log.d

public class MainActivity extends AppCompatActivity {

// TCP Connection:
private TCPClient mTcpClient;
connectTask mConnectTask;

Button connectBtn;

// Debugging variable:
private static final String TAG = MainActivity.class.getName();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Relate Button and EditText from java to the one in XML:
    connectBtn = (Button) findViewById(R.id.connectBtn);

    mConnectTask = new connectTask(); // prepare for TCP connection

    // Connect to Server after connect btn pressed
    connectBtn.setOnClickListener(
            new View.OnClickListener() {
                public void onClick(View view) {
                    Log.i(TAG, "Connect button pressed.");
                    mConnectTask.execute(); // starts Async task
                }
            }
    );
}

public class connectTask extends AsyncTask<byte[], byte[], TCPClient> {

    @Override
    protected TCPClient doInBackground(byte[]... message) {

        // Create a TCPClient object
        mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {

            @Override
            // Implementation of messageReceived method
            public void messageReceived(byte[] message) {
                publishProgress(message); // calls the onProgressUpdate method
            }

        });

        mTcpClient.run();
        return null;
    }

    @Override
    protected void onProgressUpdate(byte[]... values) {
        super.onProgressUpdate(values);

        byte b[] = values[0];

        // TODO delete
        String str = new String(b, Charset.forName("UTF-8"));
        Log.d(TAG, "Data received: " + str);

        for (int i = 0; i < b.length; i++) {
            int c = b[i] & 0xFF;
            Log.d(TAG, "c: " + c);

            // Further processing where data is needed as byte[]

        }
    }
}
}

注销接收到的数据(无法识别的字节)。但是当我注销c(它应该是接收到的字节为int)时,它总是为0。

非常感谢任何帮助:)

0 个答案:

没有答案