2016-05-05 51 views
0

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

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 demonew GitHub home

我的系统是采取的Windows 7是否操作系统需要是Windows 8的或以上?这个API的任何线索都失败了?

+0

由于升级完成函数,['WinHttpWebSocketCompleteUpgrade'](https://msdn.microsoft.com/en-us/library/windows/desktop/hh707326(V = vs.85)的.aspx)清楚地将Windows 8指定为最小平台,我将继续说,是的,你需要Windows 8或更高版本。 – WhozCraig

+0

感谢WhozCraig ....有没有什么办法可以在Win 7中使用winHttp的websockets? – Sukhas

回答

4

这里有一个非常棒的C++ WebSocket库,它可以在Windows 7中工作,它只有头文件并且只是用于提升。它带有示例代码和文档: 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"; 
}