使用java开发的程序和C++开发的程序对接,C++端使用的是ascii码
1、java接收端采用ByteBuffer接收到数据后使用GBK解码器解码
public static String getString(ByteBuffer buffer) {
Charset charset = null;
CharsetDecoder decoder = null;
CharBuffer charBuffer = null;
try {
charset = Charset.forName("GBK");
decoder = charset.newDecoder();
charBuffer = decoder.decode(buffer.asReadOnlyBuffer());
return charBuffer.toString();
} catch (Exception ex) {
//ex.printStackTrace();
return "";
}
}
2、java发送数据给C++端。
public int SendTcpData(String strData){
byte[] szCmd= new byte[1024];
int iWriteRet = 0;
byte bydata[];
try {
bydata = strData.getBytes("GBK");
System.arraycopy(bydata, 0, szCmd, 0, bydata.length);
int len = bydata.length;
ByteBuffer cacheBuffer = ByteBuffer.allocate(len);
cacheBuffer.put(szCmd,0,len);
cacheBuffer.flip();
int iWriteRet = sock.write(cacheBuffer);
if(iWriteRet<0){
}
} catch (Exception e) {
//e.printStackTrace();
}
return iWriteRet;
}