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

时间:2015-04-07 19:41:49

标签: android c++ linux sockets g++

我已经在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;

但是,我可以像下面这行一样通过char来获取它,但它很麻烦!

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

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

***********最后更新解决方案*********** Android方面:

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);

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

1 个答案:

答案 0 :(得分:1)

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

printf打印一个NUL终止的C字符串。

两者不兼容。具体而言,对于字符串&lt; 256个字节,writeUTF写的第一个字节是NUL,从而产生一个长度为0的C字符串,就像你看到的那样。

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

相关问题