PacketCodeC.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. const PacketCodeC = {
  2. encode (packet) {
  3. let bytes = stringToBytes(JSON.stringify(packet))
  4. let buffer = new ArrayBuffer(11 + bytes.length)
  5. if (buffer.byteLength !== 11 + bytes.length) {
  6. return null
  7. }
  8. let dataView = new DataView(buffer)
  9. dataView.setInt32(0, 0x12345678)
  10. dataView.setInt8(4, packet.version)
  11. dataView.setInt8(5, 1) // 写死1表示json序列化
  12. dataView.setInt8(6, packet.command)
  13. dataView.setInt32(7, bytes.length)
  14. for (let i = 11; i < bytes.length + 11; i++) {
  15. dataView.setUint8(i, bytes[i - 11])
  16. }
  17. return dataView.buffer
  18. },
  19. decode (buffer) {
  20. let dataView = new DataView(buffer)
  21. let lenght = dataView.getInt32(7)
  22. let bytes = []
  23. for (let i = 11; i < lenght + 11; i++) {
  24. bytes[i - 11] = dataView.getUint8(i)
  25. }
  26. let json = bytesToString(bytes)
  27. return JSON.parse(json)
  28. }
  29. }
  30. var stringToBytes = (str) => {
  31. let bytes = []
  32. let len, c
  33. len = str.length
  34. for (let i = 0; i < len; i++) {
  35. c = str.charCodeAt(i)
  36. if (c >= 0x010000 && c <= 0x10FFFF) {
  37. bytes.push(((c >> 18) & 0x07) | 0xF0)
  38. bytes.push(((c >> 12) & 0x3F) | 0x80)
  39. bytes.push(((c >> 6) & 0x3F) | 0x80)
  40. bytes.push((c & 0x3F) | 0x80)
  41. } else if (c >= 0x000800 && c <= 0x00FFFF) {
  42. bytes.push(((c >> 12) & 0x0F) | 0xE0)
  43. bytes.push(((c >> 6) & 0x3F) | 0x80)
  44. bytes.push((c & 0x3F) | 0x80)
  45. } else if (c >= 0x000080 && c <= 0x0007FF) {
  46. bytes.push(((c >> 6) & 0x1F) | 0xC0)
  47. bytes.push((c & 0x3F) | 0x80)
  48. } else {
  49. bytes.push(c & 0xFF)
  50. }
  51. }
  52. return bytes
  53. }
  54. var bytesToString = (bytes) => {
  55. if (typeof bytes === 'string') {
  56. return bytes
  57. }
  58. let str = ''
  59. let _arr = bytes
  60. for (let i = 0; i < _arr.length; i++) {
  61. let one = _arr[i].toString(2)
  62. let v = one.match(/^1+?(?=0)/)
  63. if (v && one.length === 8) {
  64. let bytesLength = v[0].length
  65. let store = _arr[i].toString(2).slice(7 - bytesLength)
  66. for (let st = 1; st < bytesLength; st++) {
  67. store += _arr[st + i].toString(2).slice(2)
  68. }
  69. str += String.fromCharCode(parseInt(store, 2))
  70. i += bytesLength - 1
  71. } else {
  72. str += String.fromCharCode(_arr[i])
  73. }
  74. }
  75. return str
  76. }
  77. export default PacketCodeC