我正在使用 C# 开发一个 WebSocket 服务器,我注意到使用 send() 方法来自浏览器(在这种情况下为 Chrome)的所有消息的最大长度为 126 个字符。 当我想发送大于 126 个字符的消息时,它总是发生,看起来协议(protocol)会剪切任何大于 126 个字符的消息并仅传输前 126 个字符。 我试图检查协议(protocol)定义,但没有找到任何答案。
那么,我的问题是,我可以通过 WebSockets 发送更大的消息吗?
更新: 这是我在 C# WebSocket 服务器中解析来自客户端 (Chrome) 的消息的方式:
private void ReceiveCallback(IAsyncResult _result)
{
lock (lckRead)
{
string message = string.Empty;
int startIndex = 2;
Int64 dataLength = (byte)(buffer[1] & 0x7F); // when the message is larger then 126 chars it cuts here and all i get is the first 126 chars
if (dataLength > 0)
{
if (dataLength == 126)
{
BitConverter.ToInt16(buffer, startIndex);
startIndex = 4;
}
else if (dataLength == 127)
{
BitConverter.ToInt64(buffer, startIndex);
startIndex = 10;
}
bool masked = Convert.ToBoolean((buffer[1] & 0x80) >> 7);
int maskKey = 0;
if (masked)
{
maskKey = BitConverter.ToInt32(buffer, startIndex);
startIndex = startIndex + 4;
}
byte[] payload = new byte[dataLength];
Array.Copy(buffer, (int)startIndex, payload, 0, (int)dataLength);
if (masked)
{
payload = MaskBytes(payload, maskKey);
message = Encoding.UTF8.GetString(payload);
OnDataReceived(new DataReceivedEventArgs(message.Length, message));
}
HandleMessage(message); //'message' - the message that received
Listen();
}
else
{
if (ClientDisconnected != null)
ClientDisconnected(this, EventArgs.Empty);
}
}
}
我仍然不明白我怎样才能得到更大的消息,它可能与操作码有关,但我不知道要改变什么才能让它工作?
最佳答案
WebSocket 消息可以是任意大小。但是,大消息通常分多个部分(片段)传输,以避免队头阻塞。查看WebSockets I-D了解详情。
关于c# - 如何通过 WebSocket 发送更大的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8193761/