gpt4 book ai didi

android - 无法使用套接字显示接收到的缓冲区

转载 作者:太空宇宙 更新时间:2023-11-04 10:54:13 25 4
gpt4 key购买 nike

我已经实现了一个在 Linux 中运行的 C++ 服务器来接收来自 Android 客户端的字符串。连接建立成功,字符串也接收成功(我从接收到的字节数知道!),但是,我不能一次性显示消息,我需要访问 Char 数组来显示每个字符。使用此行在 Android 上发送的数据:

dataOutputStream.writeUTF(StringToSent);

这是下面服务器的代码:

char receivedBuff[1025];    
Connection = accept(listenfd, (struct sockaddr*)NULL, NULL);
cout << "Connection accepted \n";

numOfBytes = read(Connection,receivedBuff,sizeof(receivedBuff));
if (numb < 0)
printf("ERROR reading from socket");
printf("%s\n",receivedBuff);

当我尝试使用下面的行显示接收到的缓冲区时,我什么也没得到:

cout << receivedBuff << Lendl;

但是,我可以像下面一行那样一个字符一个字符地获取它,但是它很乱!

cout << receivedBuff [0] << receivedBuff[1]  << receivedBuff[2] << endl;

我试图将 char 数组转换为 string 但它不起作用。有什么建议么?

************ 最新的解决方案更新 ***********安卓端:

PrintStream ps = null;
ps = new PrintStream(socketw.getOutputStream());
ps.println(MessageToSent +'\0');

服务器端:

 numOfBytes = read(Connection,receivedBuff,sizeof(receivedBuff));
if (numb < 0)
printf("ERROR reading from socket");
printf("%s done %d",receivedBuff, numOfBytes);

************ 最新的解决方案更新 ***********

最佳答案

DataOutputStream.writeUTF写入 16 位长度,后跟该数量的类似 UTF-8 的字节。

printf 打印以 NUL 结尾的 C 字符串。

两者不兼容。具体来说,对于 < 256 字节的字符串,writeUTF 写入的第一个字节为 NUL,从而导致长度为 0 的 C 字符串,如您所见。

由您决定通用协议(protocol)并在客户端和服务器端实现它。一个简单的例子是将字符串写成以换行符结尾的 UTF-8 编码数据:你可以用 PrintStream.println 来做到这一点。在 Java 和 std::getline在 C++ 中。

关于android - 无法使用套接字显示接收到的缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29499924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com