Rel*_*lla 6 c++ sockets boost boost-asio
根据示例创建一个简单的TCP服务器,但仍然没有得到如何创建一个读取一定数量字节的套接字,如果没有足够的将等待.我需要这不是异步操作.
#include <iostream>
#include <boost/asio.hpp>
#ifdef _WIN32
#include "Windows.h"
#endif
using namespace boost::asio::ip;
using namespace std;
int main(){
int m_nPort = 12345;
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), m_nPort));
cout << "Waiting for connection..." << endl;
tcp::socket socket(io_service);
acceptor.accept(socket);
cout << "connection accepted" << endl;
try
{
socket.send(boost::asio::buffer("Start sending me data\r\n"));
}
catch(exception &e)
{
cerr << e.what() << endl; //"The parameter is incorrect" exception
}
}
Run Code Online (Sandbox Code Playgroud)
如何接收10000个字节并执行它直到所有10000到达或1000毫秒超时并抛出异常?
Boost 1.47.0刚刚引入了一个超时功能basic_socket_iostream,即expires_at和expires_from_now方法.
以下是基于您的代码段的示例:
#include <iostream>
#include <boost/asio.hpp>
using namespace boost::asio::ip;
using namespace std;
int main(){
int m_nPort = 12345;
boost::asio::io_service io_service;
tcp::acceptor acceptor(io_service, tcp::endpoint(tcp::v4(), m_nPort));
cout << "Waiting for connection..." << endl;
tcp::iostream stream;
acceptor.accept(*stream.rdbuf());
cout << "Connection accepted" << endl;
try
{
stream << "Start sending me data\r\n";
// Set timeout in 5 seconds from now
stream.expires_from_now(boost::posix_time::seconds(5));
// Try to read 12 bytes before timeout
char buffer[12];
stream.read(buffer, 12);
// Print buffer if fully received
if (stream) // false if read timed out or other error
{
cout.write(buffer, 12);
cout << endl;
}
}
catch(exception &e)
{
cerr << e.what() << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序适用于Linux.
请注意,我并不是主张使用超时而不是使用截止时间计时器的异步操作.由你来决定.我只想表明可以实现超时basic_socket_iostream.