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

Can not display received buffer using socket

我已经实现了一个在 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 但它不起作用。有什么建议么?

*********** 最新的解决方案更新 *********** Android 边 :

PrintStream ps = null;
                ps = new PrintStream(socketw.getOutputStream());
                ps.println(MessageToSent +'[=14=]');

服务器端:

 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 字符串,如您所见。

由您决定一个通用协议并在客户端和服务器端实现它。一个简单的示例是将字符串编写为以换行符结尾的 UTF-8 编码数据:您可以在 C++ 中使用 PrintStream.println in Java and std::getline 来完成此操作。