发送大于126字节WebSocket的消息 [英] Send larger messages than 126 bytes websockets
问题描述
现在我正在研究Websocket,这是我的新手,我终于可以发送126个字节的消息,但是我需要发送更长的消息,但是当我尝试自动关闭连接时,我的代码是:>
Now I'm working on Websockets, I'm new in that, I finally can send a message of 126 bytes, but I need send longer messages but when I try the connection is closed automatically, my code is:
public void sendMessage(Stream stream, string message)
{
try
{
List<byte> lb = new List<byte>();
string aux = message;
bool flagStart = false;
int size;
while (message.Length > _maxLengthMessage)
{
lb = new List<byte>();
// I cut the mesasge in smaller pieces to send
message = aux.Substring(0, _maxLengthMessage);
aux = aux.Substring(_maxLengthMessage);
if (!flagStart)
{
// In doc of Websockets i sign this piece: not the end, text
lb.Add(0x01);
flagStart = !flagStart;
}
else
{
// In doc of Websockets i sign this piece: not the end, continuation
lb.Add(0x00);
}
size = message.Length;
lb.Add((byte)size);
lb.AddRange(Encoding.UTF8.GetBytes(message));
stream.Write(lb.ToArray(), 0, size + 2);
}
lb = new List<byte>();
if (!flagStart)
{
// If is this the only message we mark with: end of message, text
lb.Add(0x81);
flagStart = !flagStart;
}
else
{
//else Is the end of the message but is the continuation frame
lb.Add(0x80);
}
size = aux.Length;
lb.Add((byte)size);
lb.AddRange(Encoding.UTF8.GetBytes(aux));
//lb.AddRange(Encoding.UTF8.GetBytes(i.ToString()));
stream.Write(lb.ToArray(), 0, size+2);
}
catch (Exception ex)
{
throw ex;
}
}
一些答案说转到WebSocket协议",但这对我不起作用.
Some answers say "Go to the The WebSocket protocol", but it didn't work for me.
推荐答案
您编写消息长度的代码需要扩展. 协议规范显示缺少的内容.
Your code to write the message length needs to be extended. The extended payload in the data framing diagram of the protocol spec shows what's missing.
对于不超过125字节的消息,您的代码正确.
对于大于125但小于等于65536字节的消息,您需要写入3个字节-第一个字节为126;接下来的2个字节给出了消息长度.
对于大于65536字节的消息,您需要写入9个字节-第一个字节为127;接下来的8个字节给出了消息的长度.
For messages up to 125 bytes, your code is correct.
For messages > 125 but <= 65536 bytes, you need to write 3 bytes - the first byte is 126; the following 2 bytes give the message length.
For messages > 65536 bytes, you need to write 9 bytes - the first byte is 127; the following 8 bytes give the message length.
这篇关于发送大于126字节WebSocket的消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!