4 Steps To Send a Request To a Web Socket Server and Read the Response

Web socket server

WebSockets are a bidirectional computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol enables interaction between a web browser and a web server.

Send A Request

If you want to send a request to a web socket server and read the response here is a quick and easy way to do it

  1. In the example below change ‘host’, ‘port’,‘serviceName’ and ‘requestJson’ as needed.(Doesn’t need to be JSON)
  2. Will connect to the websocket server, send a request.
  3. Use a memory stream to log out the response.
  4. Read more on ClientWebsocket here: https://docs.microsoft.com/en-us/dotnet/api/system.net.websockets.clientwebsocket?view=netframework-4.5

The Example

Private Async Function Test() As Task

Dim host As String

Dim port, serviceName As String

‘WebSocket endpoint to be tested.

host = “wss://yourwebsocketurl”

port = “80”

serviceName = “test”

 

Dim server As String = String.Format(“{0}:{1}/{2}”, host, port, serviceName)

‘Some logging

Dim _log As Logger

_log = LogManager.GetCurrentClassLogger()

_log.Debug(String.Format(“Open Connection to the server. Server url is {0}”, server))

 

Dim ws = New System.Net.WebSockets.ClientWebSocket

Try

Await ws.ConnectAsync(New Uri(server), Nothing)

 

If (ws.State = WebSockets.WebSocketState.Open) Then

_log.Debug(“Connection open”)

 

‘Example of a Json login request

Dim requestJson = “{“”request””: “”Login””,””body””: {“”username””: “”User”,”password””: “”userpassword””}, “”error””: null}”

 

Dim encoded As Byte()

encoded = Encoding.UTF8.GetBytes(requestJson)

 

_log.Debug(String.Format(“Request to be sent = {0}”, requestJson))

 

Dim socketRequest = New ArraySegment(Of Byte)(encoded, 0, encoded.Length)

 

‘Send request

Await ws.SendAsync(socketRequest, WebSocketMessageType.Text, False, Nothing)

 

Dim bytes(8192) As Byte

Dim socketResponse = New ArraySegment(Of Byte)(bytes)

 

Dim result As WebSocketReceiveResult

‘Dim ms As MemoryStream

Using ms = New MemoryStream

_log.Debug(“In memeory stream”)

Do

_log.Debug(“in loop”)

result = Await ws.ReceiveAsync(socketResponse, Nothing)

ms.Write(socketResponse.Array, socketResponse.Offset, result.Count)

Loop Until result.EndOfMessage = True

 

ms.Seek(0, SeekOrigin.Begin)

If result.MessageType = WebSocketMessageType.Text Then

Using reader = New StreamReader(ms, Encoding.UTF8)

‘Result here

_log.Debug(“response is {0}”, reader.ReadToEnd())

End Using

End If

End Using

Else

_log.Debug(“Not Opened”)

End If

Catch ex As Exception

_log.Error(String.Format(“Error opening connection. Message is {0}. Inner Exception {1}”, ex.Message, ex.InnerException.ToString))

End Try

 

End Function

Contact Us

If you would like to learn more about how we are helping our clients address their critical objectives, while also building their internal capabilities and tapping into the true potential that their own resources have to offer, contact us  or call us today on 051 878555.

 

To stay up to date with Dataworks Limited news and events, connect with us via the links below:

 

 

DATAWORKS – Driving Digital Transformation in the worlds’ Leading Life Science Companies
for over 25 Years