文章目的
文章是为了记录下httpflv优化过程,服务器是rtmp推流接流服务,最后由于要在web上展示,所以使用了httpflv 和ws flv 的服务,也就是说需要一个http服务器和websocket服务器,为了灵活性,不使用其他开源的方式,而是使用c++自行实现http服务和websocket服务,当然您也可以用其他开源的库实现。
rtmp 服务选型使用了boost库的asio,使用其中的协程方式,boost库使用了1.7版本。
void start(uint16_t port)
{
asio::spawn(v_io_context,
[&](boost::asio::yield_context yield)
{
tcp::acceptor acceptor(v_io_context,
tcp::endpoint(tcp::v4(), port));
for (;;)
{
boost::system::error_code ec;
tcp::socket socket(v_io_context);
acceptor.async_accept(socket, yield[ec]);
if (!ec)
{
std::make_shared(v_io_context, std::move(socket))->go();
}
}
});
//v_io_context.run();
}
使用方法很简单,会一点c++,就可以吊起一个协程来接收链接,这个使用异步也是可以的,协程的好处是使用的时候是和阻塞编程一样,不用那么多的回调,唯一值得注意的是:异步推流到另外一台服务器时,要使用异步方式,不然会阻塞,等链接成功,再使用协程方式.这是优化之一。以下为使用方式:
//qianbo fix publish to other server here
//create push
#if 1
//如果需要推流到分布式服务器
if (CONFIG->_push_rtmp_if_pub)
{
v_hub->v_list_dm = c_rtmpclient::create_push(v_context);
v_hub->v_list_dm->v_ip = CONFIG->rtmp_push_host_.c_str();
v_hub->v_list_dm->v_port = CONFIG->rtmp_push_port_;
v_hub->v_list_dm->v_app_name = v_app_name.c_str();
v_hub->v_list_dm->v_stream_name = v_stream_name.c_str();
tcp::resolver resolver(v_context);
//asio::ip::tcp::endpoint ep(asio::ip::make_address(v_hub->v_list_dm->v_ip), v_hub->v_list_dm->v_port);
//v_hub->v_list_dm->v_endpoint = ep;
v_hub->v_list_dm->v_endpoint = resolver.resolve(CONFIG->rtmp_push_host_.c_str(),
CONFIG->v_rtmp_push_port.c_str());
//以下使用异步方式
v_hub->v_list_dm->func_do_connect();
}
客户端异步方式
void c_rtmpclient::func_do_connect()
{
asio::async_connect(v_socket, v_endpoint,
[this](boost::system::error_code ec, tcp::endpoint)
{
if (!ec)
{
start();//create the spawn program
}
else
{
//cout
关注
打赏