WebSocket Server

Developers can launch a WebSocket Server during the game and provide an RPC interface. By improving and calling these RPC interfaces, developers can monitor the internal state of the game process and increase the ability to manage the game process state.

How To Enable

The WebSocket Server is disabled by default. To enable it, add to the configuration set(USE_WEBSOCKET_SERVER ON) to the cfg.cmake file under the release package directory build/[platform]/proj (e.g.: build/android/proj by default for Android platform) generated after building the native platform.

How to use WebSocket

Refer to the example code below:

  1. // In the native platform's Release mode or in Web / WeChat Mini Games and other platforms, WebSocketServer may not be defined.
  2. if (typeof WebSocketServer == "undefined") {
  3. console.error("WebSocketServer is not enabled!");
  4. return;
  5. }
  6. let s = new WebSocketServer();
  7. s.onconnection = function (conn) {
  8. conn.ondata = function (data) {
  9. conn.send(data, (err) => {});
  10. }
  11. conn.onclose = function () {
  12. console.log("connection gone!");
  13. };
  14. };
  15. s.onclose = function () {
  16. console.log("server is closed!");
  17. }
  18. s.listen(8080, (err) => {
  19. if (!err);
  20. console.log("server booted!");
  21. });

API

The interface is defined as follows

  1. /**
  2. * Server object
  3. */
  4. class WebSocketServer {
  5. /**
  6. * Close the server
  7. */
  8. close(cb?: WsCallback): void;
  9. /**
  10. * Listen and launch the service
  11. */
  12. listen(port: number, cb?: WsCallback): void;
  13. /**
  14. * Handle new requests
  15. */
  16. set onconnection(cb: (client: WebSocketServerConnection) => void);
  17. /**
  18. * Set up the server shutdown callback
  19. */
  20. set onclose(cb: WsCallback);
  21. /**
  22. * Gets all the connection objects
  23. */
  24. get connections(): WebSocketServerConnection[];
  25. }
  26. /**
  27. * The client connection object in the server
  28. */
  29. class WebSocketServerConnection {
  30. /**
  31. * Close the connection
  32. */
  33. close(cb?: WsCallback): void;
  34. /**
  35. * Send the data
  36. */
  37. send(data: string|ArrayBuffer, cb?: WsCallback): void;
  38. set ontext(cb: (data: string) => void);
  39. set onbinary(cb: (data: ArrayBuffer) => void);
  40. set ondata(cb: (data: string|ArrayBuffer) => void);
  41. set onconnect(cb: () => void;);
  42. set onclose(cb: WsCallback);
  43. set onerror(cb: WsCallback);
  44. get readyState(): number;
  45. }
  46. interface WsCallback {
  47. (err?: string): void;
  48. }

The interface design refers to the nodejs-websocket server.