Rate This Document
Findability
Accuracy
Completeness
Readability

Setting the IP Address and Port Number of a Prototype

Application Scenario

Transfer the IP address and port number to the client communication library.

Prerequisites

You have implemented the communication library (for example, the libCommunication.so dynamic library) which provides the function for setting the IP address and port number.

Development Process

  1. Implement the function for setting the IP address and port in the JNI initialization communication library.
  2. Call the JNI to set the IP address and port number of the communication library.

Encoding Instance

// Call Java.
public class Activity implements BaseActivity { 
    protected void onCreate(Bundle savedInstanceState) { 
        if (!NetConfig.initialize()) {
           // The communication library fails to be initialized. Exit the activity.
        }
        // The third parameter indicates the communication protocol type. 0 indicates TCP.
        if (!NetConfig.setNetConfig(proxyIp, proxyPort, 0)) {
             // Set the IP address or port number of the communication library.
        }
     } 
}
 
// Implement the JNI.
JNIEXPORT jboolean JNICALL NET_CONFIG_JNI(initialize)(JNIEnv* env, jclass cls)
{
    (void) env;
    (void) cls;
    if (g_handle != nullptr) {
        return true;
    }
    // Load the communication dynamic library.
    g_handle = dlopen(LIB_COMM_NAME.c_str(), RTLD_GLOBAL | RTLD_LAZY);
    if (g_handle == nullptr) {
        ERR("error: Failed to open shared library:%s", LIB_COMM_NAME.c_str());
        return false;
    }
     // Find the ConfigNetAddress function to set the IP address and port number.
    const std::string CONFIG_NET_ADDRESS_FUNC = "ConfigNetAddress";
    g_configNetAddressFunc = reinterpret_cast<ConfigNetAddressFunc>(
        dlsym(g_handle, CONFIG_NET_ADDRESS_FUNC.c_str()));
    if (g_configNetAddressFunc == nullptr) {
        dlclose(g_handle);
        return false;
    }
    return true;
}
 
JNIEXPORT jboolean JNICALL NET_CONFIG_JNI(setNetConfig)(JNIEnv* env, jclass cls, jstring ip, jint port, jint type)
{
    (void) cls;
    (void) env;
    if (g_configNetAddressFunc == nullptr) {
        ERR("setNetConfig failed, g_configNetAddressFunc is nullptr");
        return false;
    }
    // Set the IP address and port number.
    g_configNetAddressFunc(GetIpHostOrder(Jstring2String(env, ip)), port, type);
    return true;
}