我今天尝试了一个名为 uwebsockets 的 websocket 库。我的代码只是他们 github 上提供的示例之一。
int main() {
struct PerSocketData {
};
std::vector<std::thread*> threads(std::thread::hardware_concurrency());
std::transform(threads.begin(), threads.end(), threads.begin(), [](std::thread* t) {
return new std::thread([]() {
uWS::SSLApp({
/* There are example certificates in uWebSockets.js repo */
.key_file_name = "",
.cert_file_name = "",
}).ws<PerSocketData>("/*", {
/* Settings */
.compression = uWS::SHARED_COMPRESSOR,
.maxPayloadLength = 16 * 1024,
.idleTimeout = 30,
.maxBackpressure = 1 * 1024 * 1024,
/* Handlers */
.open = [](auto* ws) {
std::cout << "connected" << std::endl;
},
.message = [](auto* ws, std::string_view message, uWS::OpCode opCode) {
ws->send(message, opCode);
},
.drain = [](auto* ws) {
/* Check getBufferedAmount here */
},
.ping = [](auto* ws) {
},
.pong = [](auto* ws) {
},
.close = [](auto* ws, int code, std::string_view message) {
}
}).listen(8443, [](auto* token) {
if (token) {
std::cout << "Thread " << std::this_thread::get_id() << " listening on port " << 8443 << std::endl;
}
else {
std::cout << "Thread " << std::this_thread::get_id() << " failed to listen on port 9001" << std::endl;
}
}).run();
});
});
std::for_each(threads.begin(), threads.end(), [](std::thread* t) {
t->join();
});}
如您所见,我没有提供密钥目录或证书目录,但在我的服务器(Windows Server 2016 IIS)上运行此示例,我能够使用https://www.websocket.org等测试站点在我的浏览器中连接到此示例/echo.html。
我认为甚至需要证书才能连接,但我没有错误并且能够连接。为什么是这样?这是我的服务器端的某种问题吗?