我在C#中成功创建了一个WebSocket服务器,我可以连接到该服务器。我按照RFC 6455的要求进行握手。
无论我发送什么(通过WebSocket.send()
)(例如“asd”),流只有9个字节的数据,UTF8“无法代表”。
using System.Net.Sockets;
using System.Net;
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Security.Cryptography;
class Server
{
public static void Main()
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
TcpClient client = server.AcceptTcpClient();
NetworkStream stream = client.GetStream();
Boolean isHandshaked = false;
while (true)
{
while (!stream.DataAvailable)
{
}
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
if (!isHandshaked)
{
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new Regex("Sec-WebSocket-Key: (.*)").Match(
Encoding.UTF8.GetString(bytes)
).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + Environment.NewLine
+ Environment.NewLine);
stream.Write(response, 0, response.Length);
isHandshaked = true;
}
else
{
Console.WriteLine(Encoding.UTF8.GetString(bytes));
}
}
}
}
我错过了什么?
答案 0 :(得分:2)
客户端和服务器之间的消息不以纯文本形式发送。请参阅标准的data framing部分,了解如何对其进行编码/解码。
对于发送3字节字符串的客户端示例,这将产生
消息您可以使用以下代码
取消屏蔽消息byte mask[4];
byte[] msg_data;
// read message, initialising mask, msg_data
for (int i=0; i<msg_data.Length; i++)
{
msg_data[i] = msg_data[i] ^ mask[i%4]
}
如果您需要更多详细信息,this previous post会解释信息发送/接收,并包含一些有用的伪代码。
答案 1 :(得分:0)
有一个空循环来检查数据,例如while (!stream.DataAvailable){}
,这是一个不好的做法,你可以避免。
read方法是blocking method
,所以它会等到数据可用
int bufferSize = 1024; // change it as you want
byte[] message = new byte[bufferSize];
readLength = stream.Read(message, 0, bufferSize);
答案 2 :(得分:0)
您可以尝试下面的代码并查看它是否有效,我怀疑您没有阅读完整的回复。
byte[] buffer = new byte[4155];
int bytesRead = 0;
using (var input = client.GetStream())
{
while (true)
{
bytesRead = input.Read(buffer, 0, buffer.Length);
totalBytes += bytesRead;
if (bytesRead > 0)
// keep processing ur data here, add it to another buffer maybe
else
break; // come out of while loop if there is no data
}
}
}