现在我正在研究Websockets,我是新手,我最终可以发送一个126字节的消息,但是我需要发送更长的消息但是当我尝试连接自动关闭时,我的代码是:
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协议”,但它对我不起作用。
答案 0 :(得分:2)
需要扩展编写消息长度的代码。 the protocol spec数据框架图中的扩展有效负载显示了缺失的内容。
对于最多125字节的消息,您的代码是正确的。
对于消息&gt; 125但是&lt; = 65536字节,你需要写3个字节 - 第一个字节是126;以下2个字节给出了消息长度。
对于消息&gt; 65536字节,需要写入9个字节 - 第一个字节为127;以下8个字节给出了消息长度。
答案 1 :(得分:1)
是的,你必须创建正确的框架,这是方法:
static private byte[] CreateFrame(string message, MessageType messageType = MessageType.Text, bool messageContinues = false)
{
byte b1 = 0;
byte b2 = 0;
switch (messageType)
{
case MessageType.Continuos:
b1 = 0;
break;
case MessageType.Text:
b1 = 1;
break;
case MessageType.Binary:
b1 = 2;
break;
case MessageType.Close:
b1 = 8;
break;
case MessageType.Ping:
b1 = 9;
break;
case MessageType.Pong:
b1 = 10;
break;
}
b1 = (byte)(b1 + 128); // set FIN bit to 1
byte[] messageBytes = Encoding.UTF8.GetBytes(message);
if (messageBytes.Length < 126)
{
b2 = (byte)messageBytes.Length;
}
else
{
if (messageBytes.Length < Math.Pow(2,16)-1)
{
b2 = 126;
}
else
{
b2 = 127;
}
}
byte[] frame = null;
if(b2 < 126)
{
frame = new byte[messageBytes.Length + 2];
frame[0] = b1;
frame[1] = b2;
Array.Copy(messageBytes, 0, frame, 2, messageBytes.Length);
}
if(b2 == 126)
{
frame = new byte[messageBytes.Length + 4];
frame[0] = b1;
frame[1] = b2;
byte[] lenght = BitConverter.GetBytes(messageBytes.Length);
frame[2] = lenght[1];
frame[3] = lenght[0];
Array.Copy(messageBytes, 0, frame, 4, messageBytes.Length);
}
if(b2 == 127)
{
frame = new byte[messageBytes.Length + 10];
frame[0] = b1;
frame[1] = b2;
byte[] lenght = BitConverter.GetBytes((long)messageBytes.Length);
for(int i = 7, j = 2; i >= 0; i--, j++)
{
frame[j] = lenght[i];
}
}
return frame;
}