现在我在HTML5中使用websocket来构建我的网络应用程序。
因为我以前的工作是基于TCP而我使用CRC16算法来包装将传输到服务器端的内容;
使用以下CRC16代码构造消息:
public static byte[] ConstructMessageWithCRC(string message)
{
//Message with a |
var messageToConstruct = message + "|";
//calculate CRC value
var crcCode = CRC16.CalculateCrc16(messageToConstruct);
var crcCodeShort = ushort.Parse(crcCode);
//CRC high value
var crcHigh = byte.Parse((crcCodeShort / 256).ToString());
//CRC low value
var crcLow = byte.Parse((crcCodeShort % 256).ToString());
var messageBytes = Encoding.Default.GetBytes(messageToConstruct);
var messageLength = messageBytes.Length;
var messageBytesWithCRC = new byte[messageLength + 2];
Array.Copy(messageBytes, 0, messageBytesWithCRC, 0, messageLength);
//append crc value to the message
messageBytesWithCRC[messageLength] = crcHigh;
messageBytesWithCRC[messageLength + 1] = crcLow;
return messageBytesWithCRC;
}
服务器端收到数据后,还会通过CRC16算法计算内容,以确保数据正确。
检查以下CRC代码:
public static bool CheckMessageCRC(byte[] message, out string messageReceived)
{
//message length that received
var messageLength = message.Length;
//message received without crc value
var messageReceivedStrBytes = new byte[messageLength - 2];
Array.Copy(message, 0, messageReceivedStrBytes, 0, messageLength - 2);
//crc value received
var messageReceivedCrcBytes = new byte[2];
Array.Copy(message, messageLength - 2, messageReceivedCrcBytes, 0, 2);
//get the received message with correct decoding
var messageCalculatedString = Encoding.Default.GetString(messageReceivedStrBytes);
messageReceived = messageCalculatedString;
//get the received crc value
var currentCRC = byte.Parse(messageReceivedCrcBytes[0].ToString()) * 256 + byte.Parse(messageReceivedCrcBytes[1].ToString());
//crc value recalculate
var result = ushort.Parse(CRC16.CalculateCrc16(messageCalculatedString));
//comparison
if (currentCRC == result)
return true;
return false;
}
从上面的代码中,你可以看到我做了什么。 但在一些使用websocket:Working with Websockets的文章中,它将使用下面的代码直接处理消息:
//When the server is sending data to this socket, this method is called
ws.onmessage = function (evt) {
//Received data is a string; We parse it to a JSON object using jQuery
//http://api.jquery.com/jQuery.parseJSON/
var jsonObject = $.parseJSON(evt.data);
//Do something with the JSON object
};
//Creates an object that will be sent to the server
var myObject = {
Property: "Value",
AnotherProperty: "AnotherValue"
};
//We need to stringify it through JSON before sending it to the server
ws.send(JSON.stringify(myJsonObject));
它将直接发送数据而不对数据进行任何检查机制。因此,如果数据被其他人拦截,我们就不会知道数据已被更改。此外,由于网络不良,数据将无法到达,然后在代码下方无法正常工作,也许我们想要数据作为ABC,但我们得到了BCA:
var jsonObject = $.parseJSON(evt.data);
因此,对于evt.data,我们想知道如何检查数据传输完成,数据顺序正确,数据内容是否正确等等。
我搜索了很多内容并且没有看到任何有关此问题的信息,只想使用此问题来声明通过websocket传输数据的正确方法,thx。
修改 我的朋友发送给我:https://tools.ietf.org/html/rfc6455,section 5.2 我认为该协议似乎已经完成了这项工作。需要更多关于它的讨论。 thx