WGShare.Client.Wx/miniprogram_npm/signalr-for-wx/HandshakeProtocol.js

68 lines
3.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 版权所有c.NET基金会。保留所有权利。
// 在2.0版Apache许可下授权。有关许可证信息请参见项目根目录中的License.txt。
import { TextMessageFormat } from "./TextMessageFormat";
import { isArrayBuffer } from "./Utils";
/**
* 握手协议
* @private
*/
var HandshakeProtocol = /** @class */ (function () {
function HandshakeProtocol() {
}
// Handshake request is always JSON - 握手请求总是JSON
HandshakeProtocol.prototype.writeHandshakeRequest = function (handshakeRequest) {
// commond
return TextMessageFormat.write(JSON.stringify(handshakeRequest));
};
/**
* 解析握手协议 response
*
* @param {*} data
* @returns {[any, HandshakeResponseMessage]}
* @memberof HandshakeProtocol
*/
HandshakeProtocol.prototype.parseHandshakeResponse = function (data) {
var responseMessage;
var messageData;
var remainingData;
// ! 删除了 @aspnet/signlaR 原有的 Buffer(仅适用 nodejs)判断
if (isArrayBuffer(data)) {
// Format is binary but still need to read JSON text from handshake response - fy: 格式是二进制的但仍然需要从握手响应中读取JSON文本
var binaryData = new Uint8Array(data);
var separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);
if (separatorIndex === -1) {
throw new Error("Message is incomplete.");
}
// content before separator is handshake response - fy:分隔符前的内容是握手响应
// optional content after is additional messages - fy:后面是附加消息的可选内容
var responseLength = separatorIndex + 1;
messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength));
remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
}
else {
var textData = data;
var separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);
if (separatorIndex === -1) {
throw new Error("Message is incomplete.");
}
// content before separator is handshake response - fy:分隔符前的内容是握手响应
// optional content after is additional messages - fy:后面是附加消息的可选内容
var responseLength = separatorIndex + 1;
messageData = textData.substring(0, responseLength);
remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
}
// At this point we should have just the single handshake message - fy: 在这一点上,我们应该只有一个握手信息
var messages = TextMessageFormat.parse(messageData);
var response = JSON.parse(messages[0]);
if (response.type) {
throw new Error("Expected a handshake response from the server. -(fy: 需要来自服务器的握手响应)");
}
responseMessage = response;
// multiple messages could have arrived with handshake - fy: 握手时可能会收到多条消息
// return additional data to be parsed as usual, or null if all parsed - fy: 返回要像往常一样分析的其他数据如果所有数据都已分析则返回null
return [remainingData, responseMessage];
};
return HandshakeProtocol;
}());
export { HandshakeProtocol };