我想要一个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上输入&#39; string始终为null。 这是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 . . .
答案 0 :(得分:0)
String input =null;
此时input
为空。
char[] buffin=new char[128];
try {
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
in.read(buffin, 0, 128);
input=String.valueOf(buffin);
此代码不正确,但如果它完全执行,则input
不可能为null。正确的代码如下:
int count = in.read(buffin);
if (count > 0)
{
input = new String(buffin, 0, count);
}
返回您的代码:
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
return input;
如果input
此时仍为空,则必须有IOException
您尚未披露。