【发布时间】:2016-05-27 04:09:19
【问题描述】:
我想要一个 android 应用程序和 Windows C++ winsock 使用 TCP 套接字进行通信,并且我成功地将一个字符串从 android 发送到 C++ 服务器,但我无法以其他方式发送字符串(从 C++ 服务器到 Android 客户端)。
这是重要的 C++ 服务器部分:
recvbuf = "Back At u \0";
cout << " \n " << recvbuf << "\n";
int iResult= send(ClientSocket, recvbuf, (int) strlen(recvbuf), 0);
if (iResult == SOCKET_ERROR) {
wprintf(L"send failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %d\n", iResult);
这里是android客户端接收部分:
class TextRcv extends AsyncTask<Void, Void, String>
{
@Override
protected String doInBackground(Void... params) {
//TO SEND A STRING
Socket clientSocket = null;
try {
clientSocket= new Socket("192.168.1.5",8889);
DataOutputStream oos= new DataOutputStream(clientSocket.getOutputStream());
oos.writeBytes(String.valueOf(mystr.length()));
oos.flush();
byte[] bufferout=mystr.getBytes();
oos.write(bufferout, 0, bufferout.length);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
//to recieve a string
String input =null;
char[] buffin=new char[128];
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
in.read(buffin, 0, 128);
input=String.valueOf(buffin);
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return input;
}
@Override
protected void onPostExecute(String input) {
super.onPostExecute(input);
Toast toast=Toast.makeText(getApplicationContext(),input,Toast.LENGTH_LONG);
toast.show();
}
}
C++ 输出表明没有错误,并且发送了 11 个字节(recvbuff 字符串的长度)。但在 android 上,“输入”字符串始终为空。 这是 c++ 服务器输出:
Start Receving
length of string recieved in bytes =14
AndroidID - Hello World...
Done
Back At u
Bytes Sent: 11
Press any key to continue . . .
【问题讨论】:
-
Android 输出在哪里?你怎么知道它是空的?注意您忽略了
read()返回的长度,并假设它填满了缓冲区。没有指定这样做。你为什么要发送两次相同的东西? -
@EJP 我知道 android 输出为空,因为 toast 出现时没有字符。我也做了 if (input==null) 检查,它是真的。
-
@EJP 我不知道你两次发送相同的东西是什么意思。请详细说明。谢谢
-
@EJP 这部分用于从 Android 发送到 C++,我首先发送字符串的大小,然后发送字符串本身。这工作没问题。问题出在代码的另一部分,我尝试将字符串从 C++ 发送到 Android。先生,您有什么解释为什么这在我的代码中不起作用?
标签: java android c++ sockets winsock