HttpRequest.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import CodeMgr from "../../scriptMain/CodeMgr"
  2. import { StringMap } from "../Collections/StringMap"
  3. import Gamecfg from "../common/gameCfg"
  4. import { gameMethod } from "../common/gameMethod"
  5. import { SevBack } from "../common/Xys"
  6. import Config from "../Config"
  7. import { GameEvent, NetworkEvent } from "../data/const/EventConst"
  8. import GameDataCenter from "../data/GameDataCenter"
  9. import GameController from "../GameController"
  10. import UIHelp, { DialogParams } from "../logic/ui/UIHelp"
  11. import EventMng from "../manager/EventMng"
  12. import { I18n } from "../utils/I18nUtil"
  13. import NetConfig from "./NetConfig"
  14. export interface POST_DATA {
  15. cmdId: number
  16. url: string,
  17. body: Object,
  18. cb1?: (sev: SevBack) => void,
  19. cb2?: (sev: SevBack) => void,
  20. deal: number
  21. postTime?: number
  22. }
  23. export default class HttpRequest {
  24. // 网络请求所需时间
  25. static netMs: number = 0
  26. // 网络请求最长时间(超时时间)
  27. static timeoutMs: number = 15000
  28. // 请求失败计数
  29. static errCount: number = 0
  30. //请求失败的接口
  31. static errPostMap: StringMap<POST_DATA> = new StringMap<POST_DATA>();
  32. //当前请求的接口
  33. static curPostMap: StringMap<POST_DATA> = new StringMap<POST_DATA>();
  34. static GET(path: string, callback: Function = () => { }) {
  35. let isJiami = this.isJiamiPlatform();
  36. let r = new XMLHttpRequest()
  37. r.open("GET", path + `?x=${isJiami ? 1 : 0}`, true)
  38. r.timeout = this.timeoutMs
  39. r.onerror = () => {
  40. console.log("发生错误,url=", path)
  41. callback({})
  42. }
  43. r.ontimeout = () => {
  44. console.log("超时了,url=", path)
  45. callback({})
  46. }
  47. r.onloadend = function () {
  48. let temp = {}
  49. if (r.status >= 200 && r.status <= 400 && r.readyState == 4) {
  50. let txt = gameMethod.xorEncrypt(r.response, isJiami);
  51. temp = JSON.parse(txt)
  52. }
  53. callback(temp)
  54. }
  55. r.send()
  56. }
  57. // 只发送,无需处理回调
  58. static POST_SIMPLE(url: string, body: Object) {
  59. let r = new XMLHttpRequest()
  60. r.open("POST", url, true)
  61. r.setRequestHeader("Content-Type", "application/json")
  62. r.send(JSON.stringify(body))
  63. }
  64. // 发送业务外,需处理回调
  65. static POST_SIMPLE_2(url: string, body: Object, callback: Function = () => { }) {
  66. let r = new XMLHttpRequest()
  67. r.open("POST", url, true)
  68. r.setRequestHeader("Content-Type", "application/json")
  69. r.onreadystatechange = () => {
  70. if (r.status >= 200 && r.status <= 400 && r.readyState == 4) {
  71. callback(r.response)
  72. } else {
  73. console.error("POST Faile:", r.status)
  74. }
  75. }
  76. r.send(JSON.stringify(body))
  77. }
  78. // 业务逻辑协议调用接口
  79. static POST(path: string, data: { [key: string]: string }, body: Object, callback: Function = () => { }, isLogin: boolean = false) {
  80. body = body || {}
  81. if (CC_JSB) {
  82. if (!gameMethod.isEmpty(GameDataCenter.sevBack) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch.clientLog)) {
  83. console.warn("C->S:", path, JSON.stringify(body))
  84. }
  85. } else {
  86. if (!gameMethod.isEmpty(GameDataCenter.sevBack) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch.clientLog)) {
  87. console.warn("C->S:", path, body)
  88. }
  89. }
  90. let delay = new Date().getTime()
  91. if (NetConfig.needWait(data.url, body)) {
  92. EventMng.emit(NetworkEvent.WAIT, 1)
  93. }
  94. //淘宝需要通过云服务调用服务器
  95. if (cc.sys.platform == cc.sys.TAOBAO_MINIGAME) {
  96. this.taoBaoCloudRequest(data, body, callback, isLogin)
  97. return
  98. }
  99. let r = new XMLHttpRequest()
  100. r.open("POST", path, true)
  101. r.timeout = this.timeoutMs
  102. r.setRequestHeader("Content-Type", "application/json")
  103. let xor: number = this.isJiamiPlatform() ? 1 : 0;//原生端接收到加密数据会不全,所以就不加密了
  104. // r.onerror = () => {
  105. // // console.warn("=======https onerror", r.status, r.readyState)
  106. // callback({ type: 0 })
  107. // if (isLogin) {
  108. // EventMng.emit(NetworkEvent.LOGIN_FAILED)
  109. // return
  110. // }
  111. // this.onError(data.url)
  112. // }
  113. r.onerror = r.ontimeout = () => {
  114. // console.warn("=======https ontimeout", r.status, r.readyState)
  115. this.netMs = r.timeout
  116. // 超时的时候,先把waiting关掉
  117. if (NetConfig.needWait(data.url, body)) {
  118. EventMng.emit(NetworkEvent.WAIT_CLOSE)
  119. }
  120. //请求失败时关闭强请求遮罩
  121. EventMng.emit(NetworkEvent.NETWAIT_MASK, false)
  122. // 如果是登录过程中出错,特殊处理
  123. if (isLogin) {
  124. EventMng.emit(NetworkEvent.LOGIN_FAILED)
  125. return
  126. }
  127. this.onTimeOut(data.url)
  128. }
  129. r.onreadystatechange = () => {
  130. // console.log("=======https onreadystatechange", r.status, r.readyState)
  131. if (r.readyState == 4) {
  132. this.netMs = new Date().getTime() - delay
  133. if (this.netMs > 1000) {
  134. console.warn("服务器回调时间超过1秒:", path, JSON.stringify(body))
  135. }
  136. }
  137. let temp = {}
  138. if (r.status >= 200 && r.status <= 400 && r.readyState == 4) {
  139. this.errCount = 0
  140. if (r.response == null || r.response == "") {
  141. EventMng.emit(NetworkEvent.ON_EXCEPTION)
  142. this.showErrDialog(data.url, data.uuid, data.version, JSON.stringify(body), r.response == null ? "null" : r.response)
  143. return
  144. }
  145. try {
  146. // temp = JSON.parse(r.response) // gameMethod.jiemi(r.response)
  147. // let jiemiTime = new Date().getTime()
  148. let txt = gameMethod.xorEncrypt(r.response, xor == 1);
  149. temp = JSON.parse(txt)
  150. // console.log("消息解密耗时:", new Date().getTime() - jiemiTime)
  151. } catch (error) {
  152. EventMng.emit(NetworkEvent.ON_EXCEPTION)
  153. console.error("解析回调数据失败:", r.response)
  154. this.showErrDialog(data.url, data.uuid, data.version, JSON.stringify(body), r.response == null ? "null" : r.response)
  155. }
  156. // try {
  157. if (temp && Object.keys(temp).length > 0) {
  158. if (CC_JSB) {
  159. if (!gameMethod.isEmpty(GameDataCenter.sevBack) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch.clientLog)) {
  160. console.warn("S->C:", JSON.stringify(temp))
  161. }
  162. } else {
  163. if (!gameMethod.isEmpty(GameDataCenter.sevBack) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch.clientLog)) {
  164. console.warn("S->C:", temp)
  165. }
  166. }
  167. //请求成功移除缓存的消息请求
  168. this.errPostMap.Remove(data.url)
  169. this.curPostMap.Remove(data.url)
  170. callback(temp)
  171. }
  172. // } catch (error) {
  173. // console.error("服务端回调数据处理时出现异常:", path, error)
  174. // }
  175. }
  176. if (r.readyState == 4 && NetConfig.needWait(data.url, body)) {
  177. EventMng.emit(NetworkEvent.WAIT, -1)
  178. }
  179. if (r.status < 200 || r.status > 400) {
  180. // 异常情况
  181. if (isLogin) {
  182. EventMng.emit(NetworkEvent.LOGIN_FAILED)
  183. } else {
  184. this.onTimeOut(data.url)
  185. }
  186. }
  187. };
  188. // r.send(JSON.stringify({ cs: CodeMgr.jiami(body) }))
  189. r.send(JSON.stringify({ xor: gameMethod.xorEncrypt(JSON.stringify(body)), x: xor }))
  190. // r.send(JSON.stringify(body))
  191. }
  192. //淘宝云服请求
  193. static taoBaoCloudRequest(data: { [key: string]: string }, body: Object, callback: Function = () => { }, isLogin: boolean = false) {
  194. let path = data.url + "?uuid=" + GameDataCenter.user.uuid +
  195. "&token=" + GameDataCenter.user.token +
  196. "&version=" + Config.appVersion +
  197. "&time=" + GameDataCenter.time.sevTime
  198. let self = this;
  199. async function taoBaoCloud() {
  200. let result
  201. try {
  202. result = await window['cloud'].application.httpRequest({
  203. //不需要完整域名,只需要接口访问路径即可
  204. 'path': path,
  205. 'method': 'POST',
  206. 'headers': { "Content-Type": "application/json" },
  207. 'params': {},
  208. 'body': { xor: gameMethod.xorEncrypt(JSON.stringify(body)) },
  209. //cloudAppId 云应用的Id
  210. 'exts': {
  211. "cloudAppId": "55088",
  212. "timeout": 4000,
  213. //空应用调用需要填写该字段,包括协议头以及端口号(可省略),支持http、https
  214. "domain": Gamecfg.packageInfo.getItem(Config.pid).wayhttp
  215. }
  216. });
  217. } catch (error) {
  218. console.log(error)
  219. }
  220. // console.log("result:", JSON.stringify(gameMethod.xorEncrypt(result)));
  221. let temp = {}
  222. try {
  223. // temp = JSON.parse(result) // gameMethod.jiemi(r.response)
  224. temp = JSON.parse(gameMethod.xorEncrypt(result))
  225. } catch (error) {
  226. EventMng.emit(NetworkEvent.ON_EXCEPTION)
  227. console.error("解析回调数据失败:", result)
  228. // self.showErrDialog(data.url, data.uuid, data.version, JSON.stringify(body), result == null ? "null" : result)
  229. }
  230. try {
  231. if (temp && Object.keys(temp).length > 0) {
  232. if (CC_JSB) {
  233. if (!gameMethod.isEmpty(GameDataCenter.sevBack) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch.clientLog)) {
  234. console.warn("S->C:", JSON.stringify(temp))
  235. }
  236. } else {
  237. if (!gameMethod.isEmpty(GameDataCenter.sevBack) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch) && !gameMethod.isEmpty(GameDataCenter.sevBack.switch.clientLog)) {
  238. console.warn("S->C:", temp)
  239. }
  240. }
  241. //请求成功移除缓存的消息请求
  242. self.errPostMap.Remove(data.url);
  243. self.curPostMap.Remove(data.url);
  244. callback(temp)
  245. }
  246. } catch (error) {
  247. console.error("服务端回调数据处理时出现异常:", error)
  248. }
  249. if (NetConfig.needWait(data.url, body)) {
  250. EventMng.emit(NetworkEvent.WAIT, -1)
  251. }
  252. }
  253. this.errCount = 0
  254. let delayTime = new Date().getTime()
  255. taoBaoCloud().then(res => {
  256. if (!gameMethod.isEmpty(GameDataCenter.sevBack?.switch?.clientLog)) {
  257. console.log("net delay time == " + (new Date().getTime() - delayTime))
  258. }
  259. });
  260. }
  261. // 发生服务器错误时,提示重试
  262. private static onError(url: string) {
  263. let dialogParam: DialogParams = {
  264. content: I18n.getI18nText("http_error", url),
  265. cbConfirm: () => {
  266. this.errCount = 0
  267. GameController.clear()
  268. cc.game.restart()
  269. },
  270. txtConfirm: I18n.getI18nText("http_overtime_confirm_1"),
  271. onlyConfirm: true
  272. }
  273. UIHelp.ShowSystemDialog(dialogParam)
  274. }
  275. // 发生服务器错误时,提示重试
  276. private static onTimeOut(url: string) {
  277. this.errCount++
  278. if (this.errCount > 3) {
  279. // 超过三次重连失败,提示退出游戏
  280. GameController.network.stopRequest = true
  281. let dialogParam: DialogParams = {
  282. content: I18n.getI18nText("http_error", url),
  283. cbConfirm: () => {
  284. this.errCount = 0
  285. GameController.clear()
  286. cc.game.restart()
  287. },
  288. txtConfirm: I18n.getI18nText("http_overtime_confirm_1"),
  289. onlyConfirm: true
  290. }
  291. UIHelp.ShowSystemDialog(dialogParam)
  292. } else {
  293. // 提示网络错误并引导重连
  294. let dialogParam: DialogParams = {
  295. content: I18n.getI18nText("http_overtime"),
  296. cbConfirm: () => {
  297. GameDataCenter.user.sendPlayerReconnect(() => {
  298. GameController.network.stopRequest = false
  299. //重连成功,重新发送失败请求
  300. this.errPostMap.Foreach((key: string, value: POST_DATA) => {
  301. console.log(`重新发送:${key}`)
  302. GameController.network.send(value.url, value.body, value.cb1, value.cb2, value.deal)
  303. })
  304. this.errPostMap.Clear()
  305. this.curPostMap.Clear()
  306. GameController.network.RemoveTimers()
  307. })
  308. },
  309. txtConfirm: I18n.getI18nText("http_overtime_confirm_2"),
  310. onlyConfirm: true
  311. }
  312. UIHelp.ShowSystemDialog(dialogParam)
  313. }
  314. }
  315. private static showErrDialog(url: string, uuid: string, version: string, body: string, response: string) {
  316. UIHelp.ShowDialog({
  317. content: "回调数据丢失,请将此界面截图给开发者\n"
  318. + `url:${url} uuid:${uuid} version:${version}\n`
  319. + `body:` + JSON.stringify(body) + "\n"
  320. + `response:${response.slice(0, 200)}`
  321. })
  322. }
  323. static isJiamiPlatform(): boolean {//以下平台不加密,因为以下加密数据会接受不全
  324. return !cc.sys.isNative && cc.sys.platform != cc.sys.VIVO_GAME && cc.sys.platform != cc.sys.XIAOMI_GAME && cc.sys.platform != cc.sys.OPPO_GAME;
  325. }
  326. }