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
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
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
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
We need your help to test this new feature and feel free to give us feedback. Thanks.