gpt4 book ai didi

javascript - 无法解码来自 Websocket 的消息

转载 作者:行者123 更新时间:2023-11-30 20:31:24 30 4
gpt4 key购买 nike

作为大学项目的一部分,我正在尝试将我的 HTML/JS 客户端连接到我的 C# 服务器,以便允许用户实时通知。 (我只需要服务器能够在任何给定时间向特定用户发送消息)

我的服务器只是一个模拟,以便在我的项目中实现它。

我成功地通过了握手阶段,我正在尝试从服务器向客户端发送一个纯字符串。我阅读了一些关于对消息进行编码是客户端不会给出“一个或多个保留位打开:reserved1 = 0,reserved2 = 1,reserved3 = 1”错误但没有成功的方式。

如何通过套接字发送原始数据并在客户端对其进行解码?

我的服务器代码:

while (true)
{
TcpListener sck = new TcpListener(IPAddress.Any, 7878);
sck.Start(1000);
TcpClient client = sck.AcceptTcpClient();

NetworkStream _stream = client.GetStream();
StreamReader clientStreamReader = new StreamReader(_stream);
StreamWriter clientStreamWriter = new StreamWriter(_stream);
while (true)
{
while (!_stream.DataAvailable) ;
Byte[] bytes = new Byte[client.Available];
_stream.Read(bytes, 0, bytes.Count());
String data = Encoding.UTF8.GetString(bytes);

if (Regex.IsMatch(data, "^GET"))
{
const string eol = "\r\n"; // HTTP/1.1 defines the sequence CR LF as the end-of-line marker

Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + eol
+ "Connection: Upgrade" + eol
+ "Upgrade: websocket" + eol
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
System.Security.Cryptography.SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new System.Text.RegularExpressions.Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + eol
+ eol);

_stream.Write(response, 0, response.Length);
}
else
{

}
}
}

我的客户代码:

<script type="text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");

// Let us open a web socket
var ws = new WebSocket("ws://localhost:7878");

ws.onopen = function () {

// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};

ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
};

ws.onclose = function () {

// websocket is closed.
alert("Connection is closed...");
};
} else {

// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>

最佳答案

我保留了上面的服务器,但添加了一个发送字符串函数和一个解码消息函数:

public static string DecodeMessage(Byte[] bytes)
{
string incomingData = string.Empty;
byte secondByte = bytes[1];
int dataLength = secondByte & 127;
int indexFirstMask = 2;
if (dataLength == 126)
indexFirstMask = 4;
else if (dataLength == 127)
indexFirstMask = 10;

IEnumerable<byte> keys = bytes.Skip(indexFirstMask).Take(4);
int indexFirstDataByte = indexFirstMask + 4;

byte[] decoded = new byte[bytes.Length - indexFirstDataByte];
for (int i = indexFirstDataByte, j = 0; i < bytes.Length; i++, j++)
{
decoded[j] = (byte)(bytes[i] ^ keys.ElementAt(j % 4));
}

return Encoding.UTF8.GetString(decoded, 0, decoded.Length);
}

public static void SendString(string userName ,string str)
{
if (!userConnections.ContainsKey(userName))
return;
TcpClient client = userConnections[userName];
NetworkStream _stream = client.GetStream();

try
{

var buf = Encoding.UTF8.GetBytes(str);
int frameSize = 64;

var parts = buf.Select((b, i) => new { b, i })
.GroupBy(x => x.i / (frameSize - 1))
.Select(x => x.Select(y => y.b).ToArray())
.ToList();

for (int i = 0; i < parts.Count; i++)
{
byte cmd = 0;
if (i == 0) cmd |= 1;
if (i == parts.Count - 1) cmd |= 0x80;

_stream.WriteByte(cmd);
_stream.WriteByte((byte)parts[i].Length);
_stream.Write(parts[i], 0, parts[i].Length);
}

_stream.Flush();
}
catch (Exception ex)
{
Console.WriteLine("Error");
}


}

其中 userConnections 是: public static Dictionary userConnections = new Dictionary();为了维护用户连接关系

关于javascript - 无法解码来自 Websocket 的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50296974/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com