TsrpcNet.ts 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /**
  2. * tsrpc连接管理
  3. */
  4. import { HttpClient as HttpClient_Browser, WsClient as WsClient_Browser } from 'tsrpc-browser';
  5. import { HttpClient as HttpClient_Miniapp, WsClient as WsClient_Miniapp } from 'tsrpc-miniapp';
  6. import { serviceProto as ServiceProtoRoom, ServiceType, ServiceType as ServiceTypeRoom } from "../shared/serviceProto";
  7. import { GameServerConfig } from './GameServerConfig';
  8. import { ShareConfig } from './ShareConfig';
  9. import { Security } from './Security';
  10. import { BaseResponse } from '../shared/base';
  11. /** TSRPC网络模块 */
  12. export class TsrpcNet {
  13. constructor() {
  14. }
  15. /**
  16. * 创建连接房间服务器 Websocket 客户端
  17. * @param serverUrl 服务器地址
  18. * @returns WsClient
  19. */
  20. createWscRoom(serverUrl: string) {
  21. // 创建客户端与房间服务器的 WebSocket 连接
  22. let wscRoom = new (cc.sys.platform == cc.sys.WECHAT_GAME ? WsClient_Miniapp : WsClient_Browser)(ServiceProtoRoom, {
  23. // server: serverUrl + "?" + Date.now(),
  24. server: serverUrl,
  25. heartbeat: {
  26. interval: GameServerConfig.heartbeat_interval,
  27. timeout: GameServerConfig.heartbeat_timeout
  28. },
  29. json: ShareConfig.json,
  30. logger: console,
  31. // logMsg: true,
  32. });
  33. this.flowClientApi(wscRoom);
  34. // this.flowAuth(wscRoom);
  35. return wscRoom;
  36. }
  37. /** HTTP 客户端协议数据加密、解密 */
  38. private flowClientApi(hc: any) {
  39. if (!ShareConfig.security) return;
  40. hc.flows.preSendDataFlow.push(v => {
  41. if (v.data instanceof Uint8Array) {
  42. v.data = Security.encrypt(v.data);
  43. }
  44. return v;
  45. });
  46. // 在处理接收到的数据之前,通常要进行加密/解密
  47. hc.flows.preRecvDataFlow.push(v => {
  48. if (v.data instanceof Uint8Array) {
  49. v.data = Security.decrypt(v.data);
  50. }
  51. return v;
  52. });
  53. }
  54. /** 帐号登录令牌验证是否逻辑(帐号中加入登录令牌,服务器通过令牌解析玩家数据,如果存在就是已登录) */
  55. private flowAuth(client: any) { // HttpClient WsClient
  56. // 执行 callApi 之前协议中插入登录令牌
  57. client.flows.preCallApiFlow.push(v => {
  58. // 请求前插入登录令牌
  59. let ssoToken = cc.sys.localStorage.getItem('SSO_TOKEN');
  60. if (ssoToken) {
  61. v.req.__ssoToken = ssoToken;
  62. }
  63. return v;
  64. })
  65. // 将 callApi 的结果返回给调用方之后将登录令牌存到本地(收到协议时将登录令牌存到本地)
  66. client.flows.postApiReturnFlow.push(v => {
  67. if (v.return.isSucc) {
  68. let res = v.return.res as BaseResponse;
  69. // 请求成功后刷新登录令牌
  70. // if (res.__ssoToken !== undefined) {
  71. // cc.sys.localStorage.setItem('SSO_TOKEN', res.__ssoToken);
  72. // }
  73. }
  74. // 登录令牌过期时删除客户端登录令牌(可跳转到登录界面)
  75. else if (v.return.err.code === 'NEED_LOGIN') {
  76. cc.sys.localStorage.setItem('SSO_TOKEN', '');
  77. }
  78. return v;
  79. });
  80. }
  81. }