Websocket Server VB.NET - Фрейм данных
Я пытаюсь создать самый простой сервер WebSocket с VB.NET. Мне удается реализовать рукопожатие, но не удается отправить сообщение после рукопожатия. Вот мой код:
Dim serverTcp As TcpListener
Dim serverThread As Thread
Sub Main()
'' Start server
serverThread = New Thread(AddressOf serverProc)
serverThread.Start()
End Sub
Private Sub serverProc()
'' Listen to port 8181
serverTcp = New TcpListener(8181)
serverTcp.Start()
Console.WriteLine("Listen to port 8181 ...")
'' Accept any connection
While (True)
Dim curSocket As Socket = serverTcp.AcceptSocket()
Dim thread As New Thread(AddressOf clientProc)
thread.Start(curSocket)
End While
End Sub
Private Sub clientProc(ByVal sck As Socket)
Dim netStream As New NetworkStream(sck)
Dim netReader As New IO.StreamReader(netStream)
Dim netWriter As New IO.StreamWriter(netStream)
Dim key As String = ""
Console.WriteLine("Accept new connection ...")
'' Reading handshake message
While (True)
Dim line As String = netReader.ReadLine()
If line.Length = 0 Then
Exit While
End If
If (line.StartsWith("Sec-WebSocket-Key: ")) Then
key = line.Split(":")(1).Trim()
End If
Console.WriteLine("Data: " & line)
End While
'' Calculate accept-key
key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
key = getSHA1Hash(key)
'' Response handshake message
Dim response As String
response = "HTTP/1.1 101 Switching Protocols" & vbCrLf
response &= "Upgrade: websocket" & vbCrLf
response &= "Connection: Upgrade" & vbCrLf
response &= "Sec-WebSocket-Accept: " & key & vbCrLf & vbCrLf
netWriter.Write(response)
netWriter.Flush()
'' Sending Hello World message
Dim message As String = "Hello World"
Dim messageByte() As Byte = System.Text.Encoding.UTF8.GetBytes(message)
Dim startByte() As Byte = {&H0}
Dim endByte() As Byte = {&HFF}
sck.Send(startByte, 1, 0)
sck.Send(messageByte)
sck.Send(endByte, 1, 0)
End Sub
Function getSHA1Hash(ByVal strToHash As String) As String
Dim sha1Obj As New Security.Cryptography.SHA1CryptoServiceProvider
Dim bytesToHash() As Byte = System.Text.Encoding.ASCII.GetBytes(strToHash)
Dim result As String
bytesToHash = sha1Obj.ComputeHash(bytesToHash)
result = Convert.ToBase64String(bytesToHash)
Return result
End Function
Стандарт говорит, что мне нужно отправить0x00
байт, следующий за байтом UTF8, и заканчивается0xFF
байт. Я сделал, как говорится, но мой HTML-клиент не может получить сообщение.
Вот мой код HTML5:
if('WebSocket' in window){
connect('ws://localhost:8181/service');
}
function connect(host) {
var ws = new WebSocket(host);
ws.onopen = function () {
alert('connected');
};
ws.onmessage = function (evt) {
alert('reveived data:'+evt.data);
};
ws.onclose = function () {
alert('socket closed');
};
};