gpt4 book ai didi

java - 为什么我的 android 客户端无法从 winsock c++ 服务器接收字符串消息?

转载 作者:行者123 更新时间:2023-11-28 05:39:26 29 4
gpt4 key购买 nike

我正在尝试构建一个 Android 应用程序,该应用程序使用 TCP 套接字与在 Windows 上运行的 C++ 服务器进行通信。我成功地从应用程序向服务器发送了一个字符串,但我不能反其道而行之。请帮助我,因为我已经尝试解决这个问题一段时间了。

安卓客户端:

String mystr="Hello World...";
char[] buffin=new char[128];
String input =null;
Integer count = 0;
class TextRcv extends AsyncTask<Void, Void, Integer>
{

@Override
protected Integer doInBackground(Void... params) {

//Sending a string (WORKING)
Socket clientSocket = null;
try {
clientSocket= new Socket("192.168.1.5",8889);
DataOutputStream oos= new DataOutputStream(clientSocket.getOutputStream());
oos.writeBytes(mystr);
//oos.writeBytes(String.valueOf(mystr.length()));//write the length of the string first
//byte[] bufferout=mystr.getBytes();
//oos.write(bufferout, 0, bufferout.length);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}

//Recieving a String (Not working)
try {
BufferedReader in = null;
if (clientSocket != null)
{
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
}
else
{
Log.e("samer ","CLIENTSOCKET NULL");
}

if (in != null)
{
count=in.read(buffin);
}
else
{
Log.e("samer ","BUFFERREADER NULL");
}

if(count>0)
{
input=new String(buffin,0,count);
}
if (clientSocket != null) {
clientSocket.close();
}

} catch (IOException e) {
Log.i("samer count: ",String.valueOf(count));//RETURNS 0 !!
Log.i("buff samer: ", String.valueOf(buffin));//Returns garbage
e.printStackTrace();
}
return count;
}

@Override
protected void onPostExecute(Integer count) {
super.onPostExecute(count);

Toast toast=Toast.makeText(getApplicationContext(),String.valueOf(count),Toast.LENGTH_LONG);
toast.show();
}
}

尽管在 Windows C++ 服务器端它表示已成功发送 25 个字节,但“计数”始终返回 0。

C++ Winsock 服务器:

int  main(int argc, const char *argv[])
{
WSADATA wsaData;
int iResult;
SOCKET ListenSocket = INVALID_SOCKET;
SOCKET ClientSocket = INVALID_SOCKET;

struct addrinfo *result = NULL;
struct addrinfo hints;
int valread;
int iSendResult;
char * recvbuf;
char *recvstr;
int recvbuflen = DEFAULT_BUFLEN;
recvbuf = (char*)malloc((recvbuflen + 1) * sizeof(char));
recvstr = (char*)malloc((recvbuflen + 1) * sizeof(char));
char* AndroidID;
char *sendbuf = "Client: sending data test";

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed with error: %d\n", iResult);

return 1;
}

ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
hints.ai_flags = AI_PASSIVE;

// Resolve the server address and port
iResult = getaddrinfo(NULL, DEFAULT_PORT, &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed with error: %d\n", iResult);
WSACleanup();

return 1;
}

// Create a SOCKET for connecting to server
ListenSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
if (ListenSocket == INVALID_SOCKET) {
printf("socket failed with error: %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();

return 1;
}

// Setup the TCP listening socket
iResult = bind(ListenSocket, result->ai_addr, (int)result->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("bind failed with error: %d\n", WSAGetLastError());
freeaddrinfo(result);
closesocket(ListenSocket);
WSACleanup();
return 1;
}

freeaddrinfo(result);

iResult = listen(ListenSocket, SOMAXCONN);
if (iResult == SOCKET_ERROR) {
printf("listen failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();

return 1;
}

// Accept a client socket
ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
printf("accept failed with error: %d\n", WSAGetLastError());
closesocket(ListenSocket);
WSACleanup();

return 1;
}

if (ClientSocket != INVALID_SOCKET)
{
cout << "Start Receving" << endl;

//------Start Receiving
//-----------------------------------
int lengthofrecv=recv(ClientSocket, recvbuf, recvbuflen, 0);
recvbuf[lengthofrecv] = '\0';//append \0 to use with printf()
AndroidID = recvbuf;
printf("AndroidID - %s \n", recvbuf);
cout << " \n Done ";

//---Start Sending to android
//-----------------------------------------
iResult = send(ClientSocket, sendbuf, (int)strlen(sendbuf), 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);

cout << WSAGetLastError() << endl;
}

// shutdown the connection since we're done
iResult = shutdown(ClientSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed with error: %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}

//cleanup
closesocket(ClientSocket);
WSACleanup();

return 0;
}

服务器控制台输出:

Start Receving

AndroidID - Hello World...

Done Bytes Sent: 25

0

Press any key to continue . . .

最佳答案

问题是您在将初始字符串发送到服务器后调用了 oos.close()

DataOutputStream 扩展了 FilterOutputStream,并记录了其 close() 方法的行为:

FilterOutputStream.close()

The close method of FilterOutputStream calls its flush method, and then calls the close method of its underlying output stream.

在这种情况下,“底层输出流”是套接字的 outputStream,它的 close() 行为也记录在案:

Socket.getOutputStream()

Closing the returned OutputStream will close the associated socket.

Socket.close()

Closes this socket.

Any thread currently blocked in an I/O operation upon this socket will throw a SocketException.

Once a socket has been closed, it is not available for further networking use (i.e. can't be reconnected or rebound). A new socket needs to be created.

Closing this socket will also close the socket's InputStream and OutputStream.

If this socket has an associated channel then the channel is closed as well.

因此,您的客户端在读取服务器的回复字符串之前关闭了套接字连接。您需要删除对 oos.close() 的调用,以便在您完成阅读之前保持连接打开。

在服务器端,由于时间原因,您的代码可能会调用 send() 并在套接字检测到断开连接之前将回复字符串放入套接字的出站缓冲区。缓冲区实际上并不是由 send() 本身传输的,它排队到 OS 内核,后者将在后台传输数据。因此,如果在检测到断开连接之前缓冲了回复字符串,send() 将返回成功而不是失败。

关于java - 为什么我的 android 客户端无法从 winsock c++ 服务器接收字符串消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37480101/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com