boost实现websocket(client)

最近需要在c++程序中用到websocket技术,上网查了一下,找到四个库:libwebsocket, websocketpp, mongoose, boost.beast. 因为项目已经依赖于boost了,而且版本也比较新1.68,可以直接用boost.beast(从boost 1.66起可用),因此就不费心搞别的了,直接用boost.beast来实现。

 

先直接从样例代码开始,做了少许修改,就实现了同步版本的客户端。

client.cpp

#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>

using tcp = boost::asio::ip::tcp;  // from <boost/asio/ip.tcp.hpp>
namespace websocket = boost::beast::websocket;  // from <boost/beast/websocket.hpp>

// Sends a WebSocket message and prints the response
int main(int argc, char** argv)
{
  try {
    // Check command line arguments.
    if (argc != 4) {
      std::cerr <<
	"Usage: client <host> <port> <text>\n" <<
	"Example:\n" <<
	"    client echo.websocket.org 80 \"Hello, world!\"\n";
      return EXIT_FAILURE;
    }
    auto const host = argv[1];
    auto const port = argv[2];
    auto const text = argv[3];

    // The io_context is required for all I/O
    boost::asio::io_context ioc;

    // These objects perform our I/O
    tcp::resolver resolver{ioc};
    websocket::stream<tcp::so
  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值