我试图使用WinHTTP连接到服务器,不幸的是,当我试图将协议从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:对WinHttpQueryOption或WinHttpSetOption的请求指定了无效的选项值。
以上代码取自微软WinHttp WebSocket演示 (https://github.com/Microsoft/Windows-classic-samples/blob/master/Samples/WinhttpWebsocket/cpp/WinhttpWebsocket.cpp)
我的系统是Windows 7,操作系统需要是Windows 8或更高版本吗?这个API有什么线索失败吗?
发布于 2016-05-12 11:46:59
这里有一个很好的C++ WebSocket库,它在Windows7中工作,它只使用头文件,只使用boost。它附带了示例代码和文档:http://vinniefalco.github.io/
这是一个向echo服务器发送消息的完整程序。这将在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";
}https://stackoverflow.com/questions/37044938
复制相似问题