我想通过蓝牙将一些字符串数据从我的Android设备传输到我的Windows笔记本电脑。 使用Microsoft提供的winsock2使用蓝牙代码示例我能够使用以下代码传输数据。不幸的是,我在我发送的字符串的开头收到一个字节顺序标记。当然,我可以简单地删除前四个字节,但这对我来说似乎有点脏。我还可以使用其他选项吗?
C ++ - 接收代码(为了更好的可读性而稍作修改 - >没有错误处理,没有评论等)
ClientSocket = accept(LocalSocket, NULL, NULL);
BOOL bContinue = TRUE;
pszDataBuffer = (char *)HeapAlloc(GetProcessHeap(),
HEAP_ZERO_MEMORY,
CXN_TRANSFER_DATA_LENGTH);
pszDataBufferIndex = pszDataBuffer;
uiTotalLengthReceived = 0;
while ( bContinue && (uiTotalLengthReceived < CXN_TRANSFER_DATA_LENGTH) ) {
iLengthReceived = recv(ClientSocket,
(char *)pszDataBufferIndex,
(CXN_TRANSFER_DATA_LENGTH - uiTotalLengthReceived),
0);
switch ( iLengthReceived ) {
case 0: // socket connection has been closed gracefully
bContinue = FALSE;
break;
case SOCKET_ERROR:
wprintf(L"=CRITICAL= | recv() call failed. WSAGetLastError=[%d]\n", WSAGetLastError());
bContinue = FALSE;
ulRetCode = CXN_ERROR;
break;
default:
pszDataBufferIndex += iLengthReceived;
uiTotalLengthReceived += iLengthReceived;
break;
}
}
if ( CXN_SUCCESS == ulRetCode ) {
pszDataBuffer[uiTotalLengthReceived] = '\0';
wprintf(L"*INFO* | Received following data string from remote device:\n%s\n", (wchar_t *)pszDataBuffer);
closesocket(ClientSocket);
ClientSocket = INVALID_SOCKET;
}
用于发送的Android代码:
OutputStream socketOutpuStream = socket.getOutputStream();
socketOutputStream.write(dataString.getBytes(Charsets.UTF_16));
答案 0 :(得分:0)
好的,我现在觉得很蠢。在同类java环境中工作多年让我完全忘记了java在使用unicodecharset作为参数调用getBytes()时设置了字节顺序标记。
在android端更改dataString.getBytes(Charsets.UTF_16)
到dataString.getBytes(StandardCharsets.UTF_16LE)
(windows是小端)后,一切都按预期工作。