将java字符串作为c / c ++字节发送

时间:2014-01-14 08:58:30

标签: java android c++ boost tcp

我正在开发一个充当TCP服务器/客户端的Android应用程序我希望将数据从应用程序发送到用c / c ++编写的服务器/客户端(使用boost libraray制作)。我有一个普通的Java函数,它调用一个本机c函数来将字符串转换为字节:

该函数定义如下(本机函数是Convert String:

// Send buffer, the method can be used by both client and server objects.
public void SendBuffer(String Buffer){

    try {
        // Convert char to string to byte
        byte[] Temp = new byte[10];

        String Teststring = "AAAAAAAABB";
        Temp = ConvertString(Teststring);

        //byte[] Temp = new String(Buffer).getBytes();

        // Get socket output stream
        OutputStream OutputBuffer = ClientSocket.getOutputStream();

        //Write byte data to outputstream
        OutputBuffer.write(Temp);  

        // Neatly flush and close the outputbuffer
        OutputBuffer.flush();
        OutputBuffer.close();
    } 
    catch (IOException e) {
        Log.e("TCPIPCommunicator: ", "Client: Failed to send", e);
        e.printStackTrace();
    }  
}

函数ConvertString是一个本机函数,它将Java字符串转换为C / C ++字符串并将其作为Java字节返回,定义如下:

JNIEXPORT jbyteArray JNICALL Java_com_example_communicationmoduleTCPIP_communicationmoduleTCPIP_ConvertString(
        JNIEnv * env, jobject,
        jstring Buffer)
{
        // Array to fill with data
        jbyteArray Array;

        // Init  java byte array
        Array = env->NewByteArray(10);

        const char* NewBuffer = env->GetStringUTFChars(Buffer, 0);


        // Set byte array region with the size of the SendData CommStruct.
        // Now we can send the data back.
        env->SetByteArrayRegion(Array, 0, 10, (jbyte*)NewBuffer);

        env->ReleaseStringUTFChars(Buffer, NewBuffer);


        // Return java array
        return Array;
    }

}

当我运行程序时,我在c侧得到两个'AAAA'但不是整个阵列(所以没有'AAAAAAAADD)。我认为问题是服务器一次发送2'AAAA'而不是整个阵列。客户端崩溃时出现以下错误:

'boost :: exception_detail :: clone_impl>'   what():read:文件结尾

java服务器是否发错了数据?任何人都可以给我一个建议吗?欢迎所有反馈!

1 个答案:

答案 0 :(得分:1)

您是否愿意发送数据或使JNI工作正常? 在前一种情况下,使用Java将字符串转换为UTF-8(英语为ASCII)。

文本字节转换[] - > byte []并不完全符合您的需要,但您会明白这一点:

//byte[] result;
//byte[] source;
String s = new String(source,"UTF-8");
result = s.getBytes("UTF-16LE");

对于第二种情况,我可以分享一部分工作代码;它调用Java将一种编码转换为另一种编码

// it returns NULL in the case of an exception
// the returned memory is calloc()'d; it's the caller's responsibility to free() it.
char* changeEncoding(const char*source, int len, int direction)
{
    JNIEnv* env = threadUnsafeInfo.env;
    jobject obj = threadUnsafeInfo.obj;

    if (!source) {
    JNU_ThrowByName(env, "java/lang/NullPointerException", 0);
    return NULL;
    }
    jbyteArray srcArray = env->NewByteArray(len);

    jclass cls = env->FindClass("com/xyz/MyClass");
    jmethodID mid = env->GetMethodID(cls, "convert", "([BI)[B");

    if (mid != NULL && srcArray != NULL) {
    env->SetByteArrayRegion(srcArray, 0, len, (jbyte*)source);
    env->ExceptionClear();

    //jbyteArray resArray = (jbyteArray)env->CallStaticObjectMethod(cls, mid, srcArray, direction);
    jbyteArray resArray = (jbyteArray)env->CallObjectMethod(obj, mid, srcArray, direction);
    if(env->ExceptionOccurred()) {
        DLOG("exception in convert ([BI)[B");
        env->ExceptionDescribe();
        //env->ExceptionClear(); // ??
        return NULL;
    }

    int resultLen = env->GetArrayLength(resArray);
    char* result = (char*)calloc(2 + resultLen,1); // why 2: a bit of healthy paranoia ain't gonna hurt anyone
    if (result == 0) {
        JNU_ThrowByName(env, "java/lang/OutOfMemoryError", 0);
        return NULL;
    }
    env->GetByteArrayRegion(resArray, 0, resultLen, (jbyte *)result);
    env->DeleteLocalRef(cls);
    env->DeleteLocalRef(resArray);
    env->DeleteLocalRef(srcArray);
    return result;
    } else {
    JNU_ThrowByName(env, "java/lang/NullPointerException", 0);
    myassert(("method id = 0",0));
    }
    return NULL;
}

在我手边的代码中 我没有使用jstrings,更喜欢字节数组。