我正在尝试使用 WinHTTP 连接到服务器,不幸的是,当我尝试将协议(protocol)从 http 升级到 webscoket 时,API WinHttpSetOption 失败。
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: A request to WinHttpQueryOption or WinHttpSetOption specified an invalid option value.
以上代码摘自Microsoft WinHttp WebSocket demo ( new GitHub home )
我的系统是Windows 7,操作系统需要是Windows 8或以上吗?这个 API 有任何失败的迹象吗?
最佳答案
这里有一个很棒的 C++ WebSocket 库,可以在 Windows 7 中运行,它仅包含 header ,并且仅使用 boost。它带有示例代码和文档: http://vinniefalco.github.io/
这是一个完整的程序,可以将消息发送到回显服务器。这适用于 Windows 7。
#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";
}
关于c++ - WinHTTP 和 Websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37044938/