我要评分
获取效率
正确性
完整性
易理解

Setting the IP Address and Port of a Prototype

Application Scenario

Transfer the IP address and port 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.

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 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 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.
    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.
    g_configNetAddressFunc(GetIpHostOrder(Jstring2String(env, ip)), port, type);
    return true;
}