在我的例子中,android应用程序应该被视为服务器,linux是客户端。我只是将数据从linux发送到android,每次发送4096字节。日志显示linux成功地发送了所有数据。
来看看服务器,也就是android。。。服务器接收数据,每次接收4096字节。但是发生了套接字错误,因为read(…)函数返回值-1;
这是我的密码:
在使用c++的linux中:
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);
}
使用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);
}
客户端发送完所有的数据,但是服务器没有接收到数据,这里是服务器的日志(android),看起来数据刚刚丢失!我认为我的代码是对的,但为什么失败了呢?
这里是服务器日志:服务器日志(android)
1条答案
按热度按时间eh57zj3b1#
逻辑上的错误是:
应该是:
我建议你使用更好的变量名。过去分词
read
是read
不是readed
.