我遇到一个问题,除非套接字或发送关闭并且循环再次迭代以在套接字上传输更多数据,否则数据不会立即传输到服务器。 我用另一个java程序测试了服务器,以确保它在它的一侧正常工作
这是代码:
#include <boost/asio.hpp>
#include <iostream>
#include "Thread.h"
using namespace std;
using namespace boost;
const char* o = new char(1);
class Stream
{
public:
Stream(string IP, int port) {
bool conncected = false;
boost::system::error_code ec;
boost::asio::io_context io_context;
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(IP), port);
boost::asio::ip::tcp::socket socket(io_context);
try {
socket.connect(endpoint);
conncected = true;
}
catch (const boost::system::system_error& e) {
std::cout << "Error: " << e.what() << std::endl;
conncected = false;
}
if (conncected)
{
Thread* mainStream = new Thread([this, &socket, &io_context,&endpoint]() {
std::vector<boost::asio::const_buffer> buffers;
while (true)
{
cout << "enter a message\n";
string message;
std::getline(std::cin, message);
message += '\n';
buffers.push_back(boost::asio::buffer(message.data(), message.size()));
auto begin = boost::asio::buffers_begin(buffers);
auto end = boost::asio::buffers_end(buffers);
boost::asio::async_write(socket, buffers,
[this, &buffers, &socket, &io_context, &endpoint](const boost::system::error_code& error, std::size_t bytes_transferred) {
if (!error) {
std::cout << "Sent " << bytes_transferred << " bytes to the server" << std::endl;
//error data is delayed untily client is closed despite this code slot being called
/*trigger an immediate transmission of data here like
socket.shutdown(socket.shutdown_send);
socket.close();
but with the stream being opened for more write
operations in the loop
*/
}
else {
std::cout << "Error sending message: " << error.message() << std::endl;
std::cout << "reconnecting to the server " << std::endl;
bool timeout = false;
new Thread([&timeout]() {Sleep(3000); timeout = true; });
while (true)
{
try {
socket.connect(endpoint);
break;
}
catch (const boost::system::system_error& e) {
if (timeout)
{
std::cout << "couldn't connect to server" << std::endl;
break;
}
}
}
}
});
io_context.run();
io_context.restart();
}
});
mainStream->join();
}
else
{
cout << "please check that connection requirements are met" << endl;
}
}
};
int main() {
new Stream("127.0.0.1", 8080);
return 0;
}
尝试过: 发送 异步发送 写一些 写
想要: 不断向服务器传输数据而不关闭套接字或流
代码有很多奇怪之处
new
导致内存泄漏在我看来你想写的可以写成
#include <boost/asio.hpp>
#include <iostream>
namespace asio = boost::asio;
void Stream(std::string IP, uint16_t port) {
using asio::ip::tcp;
using boost::system::error_code;
for (asio::system_executor ex;;) {
tcp::socket socket(ex);
connect(socket, tcp::resolver{ex}.resolve(IP, std::to_string(port)));
for (std::string message; std::cout << "enter a message: ", getline(std::cin, message);) {
message += '\n';
error_code ec;
size_t n = write(socket, asio::buffer(message), ec);
std::cout << "Sent " << n << " bytes (" << ec.message() << ")" << std::endl;
if (ec.failed())
continue; // new connection
}
}
}
int main() { //
Stream("127.0.0.1", 8080);
}