HandshakeProtocol.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. import { TextMessageFormat } from "./TextMessageFormat";
  4. import { isArrayBuffer } from "./Utils";
  5. /** @private */
  6. export class HandshakeProtocol {
  7. // Handshake request is always JSON
  8. writeHandshakeRequest(handshakeRequest) {
  9. return TextMessageFormat.write(JSON.stringify(handshakeRequest));
  10. }
  11. parseHandshakeResponse(data) {
  12. let messageData;
  13. let remainingData;
  14. if (isArrayBuffer(data)) {
  15. // Format is binary but still need to read JSON text from handshake response
  16. const binaryData = new Uint8Array(data);
  17. const separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);
  18. if (separatorIndex === -1) {
  19. throw new Error("Message is incomplete.");
  20. }
  21. // content before separator is handshake response
  22. // optional content after is additional messages
  23. const responseLength = separatorIndex + 1;
  24. messageData = String.fromCharCode.apply(null, Array.prototype.slice.call(binaryData.slice(0, responseLength)));
  25. remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
  26. }
  27. else {
  28. const textData = data;
  29. const separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);
  30. if (separatorIndex === -1) {
  31. throw new Error("Message is incomplete.");
  32. }
  33. // content before separator is handshake response
  34. // optional content after is additional messages
  35. const responseLength = separatorIndex + 1;
  36. messageData = textData.substring(0, responseLength);
  37. remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
  38. }
  39. // At this point we should have just the single handshake message
  40. const messages = TextMessageFormat.parse(messageData);
  41. const response = JSON.parse(messages[0]);
  42. if (response.type) {
  43. throw new Error("Expected a handshake response from the server.");
  44. }
  45. const responseMessage = response;
  46. // multiple messages could have arrived with handshake
  47. // return additional data to be parsed as usual, or null if all parsed
  48. return [remainingData, responseMessage];
  49. }
  50. }
  51. //# sourceMappingURL=HandshakeProtocol.js.map