Sample code for 30+ languages & platforms
Android™

Receive a 4-byte Length Prefix from a Socket

See more Socket/SSL/TLS Examples

Demonstrates Socket.ReceiveCount, which reads a four-byte length prefix as a signed 32-bit integer. A return value of -1 indicates failure.

Background. Reading the length prefix first tells the application exactly how many bytes to read for the message body, which is a reliable way to know when a full message has arrived.

Chilkat Android™ Downloads

Android™
// Important: Don't forget to include the call to System.loadLibrary
// as shown at the bottom of this code sample.
package com.test;

import android.app.Activity;
import com.chilkatsoft.*;

import android.widget.TextView;
import android.os.Bundle;

public class SimpleActivity extends Activity {

  private static final String TAG = "Chilkat";

  // Called when the activity is first created.
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean success = false;

    CkSocket socket = new CkSocket();

    //  Connect to the server using TLS.
    boolean bTls = true;
    int maxWaitMs = 5000;
    success = socket.Connect("example.com",5000,bTls,maxWaitMs);
    if (success == false) {
        Log.i(TAG, socket.lastErrorText());
        return;
        }

    //  Read a four-byte length prefix as a signed 32-bit integer (network byte order by default).  A
    //  return value of -1 indicates failure.
    int messageLength = socket.ReceiveCount();
    if (messageLength < 0) {
        Log.i(TAG, socket.lastErrorText());
        return;
        }

    Log.i(TAG, "The peer will send " + String.valueOf(messageLength) + " bytes.");

  }

  static {
      System.loadLibrary("chilkat");

      // Note: If the incorrect library name is passed to System.loadLibrary,
      // then you will see the following error message at application startup:
      //"The application <your-application-name> has stopped unexpectedly. Please try again."
  }
}