首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WinHTTP和Websocket

WinHTTP和Websocket
EN

Stack Overflow用户
提问于 2016-05-05 07:30:12
回答 1查看 4.1K关注 0票数 0

我试图使用WinHTTP连接到服务器,不幸的是,当我试图将协议从http升级到webscoket时,API WinHttpSetOption失败了。

代码语言:javascript
复制
hSessionHandle    = WinHttpOpen(L"WebSocket sample",WINHTTP_ACCESS_TYPE_NO_PROXY,NULL,  NULL,0);
hConnectionHandle = WinHttpConnect(hSessionHandle, L"localhost",INTERNET_DEFAULT_HTTP_PORT, 0);
hRequestHandle    = WinHttpOpenRequest(hConnectionHandle,L"GET",L"/ws",NULL,NULL,NULL,  0);

// Request protocol upgrade from http to websocket.
fStatus = WinHttpSetOption(hRequestHandle,WINHTTP_OPTION_UPGRADE_TO_WEB_SOCKET,NULL,0);
if (!fStatus)
{
   dwError = GetLastError();
   goto quit;
}

fStatus返回FALSE,GetLastError返回错误代码12009,如下所示

ERROR_WINHTTP_INVALID_OPTION 12009:对WinHttpQueryOption或WinHttpSetOption的请求指定了无效的选项值。

以上代码取自微软WinHttp WebSocket演示 (https://github.com/Microsoft/Windows-classic-samples/blob/master/Samples/WinhttpWebsocket/cpp/WinhttpWebsocket.cpp)

我的系统是Windows 7,操作系统需要是Windows 8或更高版本吗?这个API有什么线索失败吗?

EN

回答 1

Stack Overflow用户

发布于 2016-05-12 11:46:59

这里有一个很好的C++ WebSocket库,它在Windows7中工作,它只使用头文件,只使用boost。它附带了示例代码和文档:http://vinniefalco.github.io/

这是一个向echo服务器发送消息的完整程序。这将在Windows 7中为您工作。

代码语言:javascript
复制
#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";
}
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37044938

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档