问题描述
我正在尝试在 vb.net 中编写一个简单的 WebSocket 服务器.我能够建立连接并将数据从服务器发送到客户端.我无法解码客户端发送的帧.我只能解码其中的一部分.
I'm trying to write a simple WebSocket server in vb.net. I am able to establish connection and send data from server to client. I'm failing at decoding frames sent from client. I am able to decode only part of it.
我试图从这个答案中实现伪代码:我如何发送和接收...,但正如我所说 - 我只能解码帧的一部分.
I was trying to implement pseudo-code from this answer: How can I send and receive..., but as I've said - I am able to decode only part of the frame.
这是我从客户端解码帧的代码:
This is my code for decoding frames from client:
bytesLen = netStream.Read(bytesArray, 0, bytesArray.Length)
If bytesArray.Length > 1 Then
Msg("---------------------------------------------------")
Msg("data type: " & bytesArray(0))
Dim secondByte As Byte = bytesArray(1)
Dim theLength As UInteger = secondByte And 127
Dim indexFirstMask As Integer = 2
If theLength = 126 Then
indexFirstMask = 4
ElseIf theLength = 127 Then
indexFirstMask = 10
End If
Msg("indexFirstMask: " & indexFirstMask)
Dim masks As New List(Of Byte)
Dim x As Integer = indexFirstMask
While (x < indexFirstMask + 4)
masks.Add(bytesArray(x))
x += 1
End While
Dim indexFirstDataByte = indexFirstMask + 4
Dim decoded(bytesLen - indexFirstDataByte) As Byte
Dim i As Integer = 0, j As Integer = 0
For i = indexFirstDataByte To bytesLen Step 1
Dim mask As Byte = masks(j Mod 4)
Dim encodedByte As Byte = bytesArray(i)
decoded(j) = (encodedByte Xor mask)
j += 1
Next
Msg("FROM CLIENT: '" & System.Text.Encoding.UTF8.GetString(decoded) & "'")
SendMessage(sck, "CONNECTION_OK")
End If
我已经多次检查了这段代码,每次我都找不到与上面答案中的伪代码有任何区别.
I've inspected this code many times and every time I couldn't find any differences between pseudo-code from the answer above.
我做错了什么?
推荐答案
我自己解决了我的问题.有修复:
I have fixed my problem myself. There's fix:
Dim indexFirstMask As Integer = 1
If theLength = 126 Then
indexFirstMask = 3
ElseIf theLength = 127 Then
indexFirstMask = 9
End If
这篇关于WebSocket 服务器,客户端 ->服务器框架掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!