【问题标题】:iostream like networking in C++?iostream 像 C++ 中的网络?
【发布时间】:2014-05-28 10:20:31
【问题描述】:

是否可以在 C++ 中像网络一样进行流式处理?

类似:

sstream<"www.google.com"> google;
sstream<socket_data> data;
google << "hello";//send hello
google >> data;//read response
if(data.size() > 0)//ok
{
    //manipulate data
}

如果是,如何?

我找不到有关此主题的任何信息。

【问题讨论】:

  • 那很好,但它绝对不是标准的c++。也许有些图书馆支持它。
  • 也许您想要卡萨布兰卡图书馆之类的东西? casablanca.codeplex.com
  • @Kiroxas 如果它可以构建在具有 4GB 硬盘空间的 Raspberry PI 上,那看起来很酷 :) 但仍然想知道一些轻量级的东西。我认为 4 GB 不足以提升。 (我确实非常喜欢 boost,但它不适合这样的迷你电脑)。
  • 您可以编写自己的streambufs 和streams,i/o 库被设计为可扩展的。
  • 你考虑过boost asio吗?参见例如here 获取相关问题和示例代码链接,或者例如here for an SSL example

标签: c++ networking wrapper iostream


【解决方案1】:

我写了跨平台网络,你可以在这里找到源代码: https://bitbucket.org/ptroen/crossplatformnetwork/src/master/(它建立在 boost::asio 之上)

该库在获得高性能的同时相当多地概括了网络协议。例如,这将是一个 http 客户端(从 https://bitbucket.org/ptroen/crossplatformnetwork/src/master/OSI/Application/Stub/HTTPClient/main.cc 提取) OSI::Transport::Interface::IClientTransportInitializationParameters init_parameters; init_parameters.ParseServerArgs(&(*argv), argc, 80, 80);

OSI::Transport::HTTP::HTTPClientTransport<SampleProtocol::IncomingPayload<OSI::Transport::Interface::IClientTransportInitializationParameters>, SampleProtocol::OutgoingPayload<OSI::Transport::Interface::IClientTransportInitializationParameters>, SampleProtocol::SampleProtocolClientSession<OSI::Transport::Interface::IClientTransportInitializationParameters>, OSI::Transport::Interface::IClientTransportInitializationParameters> client(init_parameters);
SampleProtocol::IncomingPayload< OSI::Transport::Interface::IClientTransportInitializationParameters> request(init_parameters);
client.RunClient((char*)init_parameters.ipAddress.c_str(), request);

SampleProtocol 只是一个类,其方法由模板调用(请参阅 size()、max_size()、ToString() 和 FromString(),但如果您赶时间,您可能只使用它作为您的有效负载。

通过一些工作,您可以使用类似 sstream 的接口将其包装以实现网络 iostream 效果,如果您需要提取器,甚至可以在内部将其传递给 sstream。例如,这里是关于如何从 std::ostream https://horstmann.com/cpp/iostreams.html 派生的参考(它用于不同的用例,但很好的参考读物)。

制作网络流库的方法如下:

  1. 创建一个类似于 sstream 的类,重载提取运算符以传入字符串,反之亦然。
  2. 在构造函数中创建一个新线程(通过 std::thread)来调用上面的网络代码
  3. 在示例协议中添加std::atomic 或tostring 中的互斥体,并从string 中将异步消息传回主线程。基本上,当您需要一种机制将有效负载准备好传递回主线程时,您的 iostream 包装器可以在主线程上获取它。或者您可以执行不需要线程的阻塞(https://www.tutorialspoint.com/what-is-blocking-networks-and-non-blocking-networks-in-computer-architecture)实现,但您的网络性能会更差(因为您的阻塞)。

如果你想阻塞,你可以在命令行上使用调用 curl(如果 windows 安装 cgywin,请参见此处https://linuxize.com/post/curl-command-examples/),这样就不需要单独的线程。调用 curl 后获取流,解析命令行响应并将其传递回字符串并插入到 iostream 类中。这种 curl 方法的另一个缺点是您基本上必须实现各种 http 客户端解析器。

祝你有美好的一天:)

【讨论】:

    猜你喜欢
    • 2010-11-18
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-28
    • 2013-01-18
    相关资源
    最近更新 更多