boost :: asio是否支持websocket? [英] Does boost::asio support websockets?

查看:883
本文介绍了boost :: asio是否支持websocket?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发布了问题早先询问为什么我的服务器(用C ++和boost::asio编写)无法与客户端(用Javascript编写)连接. Javascript Websocket与boost::asio套接字是否不同? boost::asio不支持websockets吗?解决这个问题的最简单方法是什么?

I posted a question earlier asking why does my server (written in C++ and boost::asio) can't connect with a client (written in Javascript). Is the problem that the Javascript Websockets are different than boost::asio sockets ? Does boost::asio not support websockets ? What is the easiest way to work this out ?

推荐答案

Boost.Asio不直接支持WebSocket,但是那里有一个很棒的开源库,它非常类似于Boost.Asio,并且可以按照您的方式工作预计.您可以尝试一下,仅使用标头,仅使用boost.它附带示例代码和文档: http://vinniefalco.github.io/

Boost.Asio doesn't directly support WebSocket but there's this great open source library out there which is very closely modeled to Boost.Asio and works the way that you expect. You might give it a try, its header-only and uses just boost. It comes with example code and documentation: http://vinniefalco.github.io/

这是一个完整的程序,可将消息发送到回显服务器:

Here's a complete program that sends a message to the echo server:

#include <beast/websocket.hpp>
#include <beast/buffers_debug.hpp>
#include <boost/asio.hpp>
#include <iostream>
#include <string>

int main()
{
    // Normal boost::asio setup
    std::string const host = "echo.websocket.org";
    boost::asio::io_service ios;
    boost::asio::ip::tcp::resolver r(ios);
    boost::asio::ip::tcp::socket sock(ios);
    boost::asio::connect(sock,
        r.resolve(boost::asio::ip::tcp::resolver::query{host, "80"}));

    using namespace beast::websocket;

    // WebSocket connect and send message using beast
    stream<boost::asio::ip::tcp::socket&> ws(sock);
    ws.handshake(host, "/");
    ws.write(boost::asio::buffer("Hello, world!"));

    // Receive WebSocket message, print and close using beast
    beast::streambuf sb;
    opcode op;
    ws.read(op, sb);
    ws.close(close_code::normal);
    std::cout <<
        beast::debug::buffers_to_string(sb.data()) << "\n";
}

这篇关于boost :: asio是否支持websocket?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆