【发布时间】:2015-06-12 13:00:20
【问题描述】:
我已经实现了一个在 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 数组转换为字符串,但它不起作用。有什么建议?
*********** 解决方案的最后更新 *********** 安卓端:
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);
*********** 解决方案的最后更新 ***********
【问题讨论】:
-
请准确显示StringToSend的内容并告诉我们numOfBytes的值。
-
添加收到的Buff[numOfBytes]=0;
-
StringToSent = "ABCD" numOfBytes= 6 我发送的每条消息都添加了 2 个字节我不知道为什么,如果 StringToSent = "AB" 那么 numOfBytes 将为 4。
-
'每条消息添加 2 个字节'。你不会告诉在哪里?前面还是后面?
-
@greenapps 感谢您的关注,我已在 android 上将 dataOutputStream 替换为 PrintStream.println ,现在它不会添加任何额外的字节。在服务器端它填补空白的空间,像这样零:谢谢你绿色应用00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000完成21个字节 SPAN>
标签: android c++ linux sockets g++