我正在尝试使用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的请求指定了无效的选项值。
上面的代码摘自Microsoft WinHttp WebSocket demo(new GitHub home)
我的系统是Windows7。操作系统是否需要是Windows 8或更高版本?这个API的任何线索失败了吗?
最佳答案
这里有一个很棒的C ++ WebSocket库,可在Windows 7中使用,它仅用于标头,仅使用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/