WebSocket服务器,客户端 - >服务器帧掩码

时间:2014-07-13 11:00:19

标签: vb.net sockets websocket

我正在尝试在vb.net中编写一个简单的WebSocket服务器。我能够建立连接并从服务器发送数据到客户端。我无法解码客户端发送的帧。我只能解码部分内容。

我试图从这个答案中实现伪代码:How can I send and receive...,但正如我所说 - 我只能解码部分帧。

Messages from client Messages after decoding

这是我从客户端解码帧的代码:

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

我多次检查过这段代码,每次在上面的答案中找不到伪代码之间的差异。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我自己解决了问题。有修复:

Dim indexFirstMask As Integer = 1
If theLength = 126 Then
    indexFirstMask = 3
ElseIf theLength = 127 Then
    indexFirstMask = 9
End If