Created
February 20, 2020 14:24
-
-
Save SteveSandersonMS/5aaff6b010b0785075b0a08cc1e40e01 to your computer and use it in GitHub Desktop.
Blazor WebAssembly use of ClientWebSocket
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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); | |
} | |
} |
https://websocket.org is no longer available, long live Postman Raw Echo Socket Service. Read more here: Introducing Postman’s WebSocket Echo Service
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
Are you hitting a Serverless HTTP Trigger with SignalR Service with this implementation?