Reputation: 43
In my case,Android App should be regarded as a Server and linux is the client. I just send data from linux to Android with 4096 bytes per send. The log shows that linux sends all data successfully.
Here come to the Server, i.e Android... Server receives data with 4096 bytes per receive. But socket error happened because the read(...) function return the value -1;
Here is my code:
In linux with c++:
auto size = static_cast<int>(buffer.size()); // buffer is the data needed to send;
auto bytes_send = 0, bytes = 0;
printf("target. data size needed to send: %d\n", size);
int single = 4096;
while(bytes_send < size){
int remain = size - bytes_send;
if(remain < single){
bytes = send(socket_client_fd, &buffer[bytes_send], remain, 0);
} else {
bytes = send(socket_client_fd, &buffer[bytes_send], single, 0);
}
if(bytes < 0){
std::cerr:: "Failed to send data" << std::endl;
return;
}
bytes_send += bytes;
printf("This remain: %d; We send %d bytes; Totally %d bytes sended;\n", remain, bytes, bytes_send);
}
And the server with java:
// previously got size need to receive
byte[] bytes = new byte[size];
int bytes_recved = 0;
int single = 4096;
while(bytes_recved < size){
int remain = size - bytes_recved;
int read = -1;
if(remain < single)
read = inputStream.read(bytes, bytes_recved , remain);
else
read = inputStream.read(bytes, bytes_recved , single);
if(read < 0){
Log.i(TAG, "received failed, less than 0 bytes " + read);
break;
}
bytes_recved += read;
Log.i(TAG, "received: " + bytes_recved + " ; receive this time: " + read);
}
Client send all data completely, but Server failed to received data, here is the log of Server(Android),It seems that data just lost! I think my code is right, but why it failed?
Here is the log of server: The log of Server(Android)
Upvotes: 1
Views: 85
Reputation: 11209
The logical mistake is this:
if(readed < 0)
It should be:
if(read < 0)
I advise you to use better variable names. The past participle of read
is read
not readed
.
Upvotes: 1