我有使用 boost.asio 和 php 客户端用 C++ 编写的服务器。当我发送少量数据时,我得到了所有数据,但是当我发送长字符串时,我丢失了大部分数据。
这是我从我的服务器发送数据的部分,它说我已经发送了 65536 字节
void handle_write(const boost::system::error_code& /*error*/,
size_t size/*bytes_transferred*/) {
cout <<size<<endl;
}
void handler_read(const boost::system::error_code&, std::size_t size) {
istream is(&buffer);
string myString;
getline(is, myString);
Manager myManager(myString);
string response = myManager.getResponse();
boost::asio::async_write(socket_,
boost::asio::buffer(response),
boost::bind(&tcp_connection::handle_write, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
这里我制作了我要发送的字符串
string getMap(string name, string pass) {
if (name == "admin" && pass == "123") {
string response = "";
ConvertTypes types;
response = types.intToString(MAP_HEIGHT) + " ";
response += types.intToString(MAP_WIDTH) + "\r\n";
for (int i=0; i<MAP_HEIGHT;i++) {
for (int j=0;j<MAP_WIDTH;j++) {
response += types.intToString(
worldMap[i][j].getHeight()) + " ";
response += types.intToString(
worldMap[i][j].getIsTown()) + " ";
response += string (1, worldMap[i][j].getTetrain())
+"\r\n";
}
}
return response;
} else {
return "";
}
}
在 php 端,我读取了发送的数据,stream_get_meta_data 说我只收到了 8183 字节的数据。
print_r($this->socket->getStatus());
for ($i=0; $i<$MAP_HEIGHT;$i++) {
for ($j=0; $j<$MAP_WIDTH;$j++) {
$this->response = $this->socket->readLine();
$this->response = explode(' ', $this->response);
echo "<p>";
echo "$i $j <br>";
print_r($this->response);
echo '<br>';
print_r($keyArray);
$map[$i][$j] = array_combine($keyArray, $this->response);
$this->response = $this->socket->readLine();
} }
}
最佳答案
您可以通过套接字发送一个大块,但接收端可能会收到几个较小的 block ,例如:
send -> 10000 bytes
receive <- 3000 bytes
receive <- 2000 bytes
receive <- 4500 bytes
receive <- 500 bytes
这只是一个示例,TCP 不保证发送和接收 block 的大小相同。
关于php - 发送和接收的数据大小不一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5341258/