As we know, Apple to require HTTPS encryption on all iOS apps by 2017 in WWDC 2016.
But in the latest Cocos2d-X, WebSocket SSL Connections is still not supported. Many developers have required this feature, and yes, it should be supported in Cocos2d-X.
We uses a 3rd-party websocket library called libwebsockets
(https://github.com/warmcat/libwebsockets) . We wrapped the interfaces and make it more easier use for our developers. The wrapper code could be found at cocos/network/WebSocket.h/.cpp
.
To support SSL for WS isnât as easy as you guess. We have to build OpenSSL libraries for all platforms and rebuild libwebsockets
library to enable SSL support.
And totally refactored WebSocket class to make it support SSL. The Pull Request is https://github.com/cocos2d/cocos2d-x/pull/17172.
WHY DO WE HAVE TO REFACTOR A LOT ?
Since before, each WebSocket class will use a sub-thread and maintain an independent libwebsockets context.
Therefore, if you create many WebSocket instances at the same time, there will be as many thread/context as the instances.
This old way will not work by just rebuilding libwebsockets
library. Crashes will be triggered while initializing libwebsockets
context because libwebsockets
or openssl
isnât thread-safe.
I finally found a way, thatâs using only one context for all WebSocket instances, uses the feature of virtual host
in libwebsockets
to simulate different Websocket client.
Then, there will be only one thread, one libwebsockets context, some libwebsockets instances, some virtual hosts for all WebSocket
instances. So the refactoring is a lot.
HOW TO USE TO SUPPORT SSL CONNECTION?
Itâs really as easy as before. Just notice the init
method.
Before, we use
auto ws = new WebSocket();
ws->init("ws://echo.websocket.org");
to make a non-ssl connection.
Currently, we use
auto ws = new WebSocket();
ws->init("wss://echo.websocket.org", nullptr, "your CA root file path");
to make a SSL connection.
CA Root file could be exported from your browser or just use which in curl
(http://curl.haxx.se/ca/cacert.pem)
We need your help to test this new feature and feel free to give us feedback. Thanks.
James