Skip to content

Instantly share code, notes, and snippets.

@SteveSandersonMS
Created February 20, 2020 14:24
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save SteveSandersonMS/5aaff6b010b0785075b0a08cc1e40e01 to your computer and use it in GitHub Desktop.
Save SteveSandersonMS/5aaff6b010b0785075b0a08cc1e40e01 to your computer and use it in GitHub Desktop.
Blazor WebAssembly use of ClientWebSocket
@page "/"
@using System.Net.WebSockets
@using System.Text
@using System.Threading
@implements IDisposable
<h1>Echo test</h1>
<h3>State: @webSocket.State</h3>
@if (webSocket.State == WebSocketState.Open)
{
<form @onsubmit="@SendMessageAsync">
Message: <input @bind="@message" />
<button type="submit">Send</button>
</form>
<pre>@log</pre>
}
@code {
CancellationTokenSource disposalTokenSource = new CancellationTokenSource();
ClientWebSocket webSocket = new ClientWebSocket();
string message = "Hello, websocket!";
string log = "";
protected override async Task OnInitializedAsync()
{
await webSocket.ConnectAsync(new Uri("wss://echo.websocket.org"), disposalTokenSource.Token);
_ = ReceiveLoop();
}
async Task SendMessageAsync()
{
log += $"Sending: {message}\n";
var dataToSend = new ArraySegment<byte>(Encoding.UTF8.GetBytes(message));
await webSocket.SendAsync(dataToSend, WebSocketMessageType.Text, true, disposalTokenSource.Token);
}
async Task ReceiveLoop()
{
var buffer = new ArraySegment<byte>(new byte[1024]);
while (!disposalTokenSource.IsCancellationRequested)
{
// Note that the received block might only be part of a larger message. If this applies in your scenario,
// check the received.EndOfMessage and consider buffering the blocks until that property is true.
// Or use a higher-level library such as SignalR.
var received = await webSocket.ReceiveAsync(buffer, disposalTokenSource.Token);
var receivedAsText = Encoding.UTF8.GetString(buffer.Array, 0, received.Count);
log += $"Received: {receivedAsText}\n";
StateHasChanged();
}
}
public void Dispose()
{
disposalTokenSource.Cancel();
_ = webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Bye", CancellationToken.None);
}
}
@f9analytics
Copy link

Are you hitting a Serverless HTTP Trigger with SignalR Service with this implementation?

@gragra33
Copy link

https://websocket.org is no longer available, long live Postman Raw Echo Socket Service. Read more here: Introducing Postman’s WebSocket Echo Service

@ph0rd
Copy link

ph0rd commented Apr 19, 2023

To make this code work, do this:
On line 28, replace "wss://echo.websocket.org" with "wss://ws.postman-echo.com/raw"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment