Skip to content

Commit

Permalink
Implement Blazor sample application
Browse files Browse the repository at this point in the history
  • Loading branch information
Marfusios committed Nov 20, 2021
1 parent 99622b4 commit a9954a3
Show file tree
Hide file tree
Showing 37 changed files with 1,489 additions and 8 deletions.
11 changes: 9 additions & 2 deletions Websocket.Client.sln
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27130.2010
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{360B18BD-653A-4824-9261-C88167EEBAD2}"
EndProject
Expand All @@ -24,6 +24,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Websocket.Client.Tests.Inte
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Websocket.Client.Sample", "test_integration\Websocket.Client.Sample\Websocket.Client.Sample.csproj", "{085B9246-446B-4F61-A6EF-0D8949CA546D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Websocket.Client.Sample.Blazor", "test_integration\Websocket.Client.Sample.NetFramework\Websocket.Client.Sample.Blazor\Websocket.Client.Sample.Blazor.csproj", "{B33B995C-CF0B-4E76-8021-D85CC93DA1A7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -46,6 +48,10 @@ Global
{085B9246-446B-4F61-A6EF-0D8949CA546D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{085B9246-446B-4F61-A6EF-0D8949CA546D}.Release|Any CPU.ActiveCfg = Release|Any CPU
{085B9246-446B-4F61-A6EF-0D8949CA546D}.Release|Any CPU.Build.0 = Release|Any CPU
{B33B995C-CF0B-4E76-8021-D85CC93DA1A7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B33B995C-CF0B-4E76-8021-D85CC93DA1A7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B33B995C-CF0B-4E76-8021-D85CC93DA1A7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B33B995C-CF0B-4E76-8021-D85CC93DA1A7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand All @@ -55,6 +61,7 @@ Global
{A34F25AA-365F-4709-A642-7B21743C91D7} = {0544BC01-B569-4729-86B0-5AFDBF7EED46}
{FAFB1608-8DFF-4DDA-81D3-36385582DA07} = {42E4078C-4FBE-4B03-B889-1573332945A9}
{085B9246-446B-4F61-A6EF-0D8949CA546D} = {42E4078C-4FBE-4B03-B889-1573332945A9}
{B33B995C-CF0B-4E76-8021-D85CC93DA1A7} = {42E4078C-4FBE-4B03-B889-1573332945A9}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EE3E0B94-CF20-4C22-B50B-E720E8DFD675}
Expand Down
9 changes: 5 additions & 4 deletions src/Websocket.Client/WebsocketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,11 @@ public WebsocketClient(Uri url, Func<Uri, CancellationToken, Task<WebSocket>> co
_url = url;
_connectionFactory = connectionFactory ?? (async (uri, token) =>
{
var client = new ClientWebSocket
{
Options = { KeepAliveInterval = new TimeSpan(0, 0, 5, 0) }
};
//var client = new ClientWebSocket
//{
// Options = { KeepAliveInterval = new TimeSpan(0, 0, 5, 0) }
//};
var client = new ClientWebSocket();
await client.ConnectAsync(uri, token).ConfigureAwait(false);
return client;
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
@page "/counter"

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
private int currentCount = 0;

private void IncrementCount()
{
currentCount++;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
@page "/fetchdata"
@inject HttpClient Http

<PageTitle>Weather forecast</PageTitle>

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from the server.</p>

@if (forecasts == null)
{
<p><em>Loading...</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>Date</th>
<th>Temp. (C)</th>
<th>Temp. (F)</th>
<th>Summary</th>
</tr>
</thead>
<tbody>
@foreach (var forecast in forecasts)
{
<tr>
<td>@forecast.Date.ToShortDateString()</td>
<td>@forecast.TemperatureC</td>
<td>@forecast.TemperatureF</td>
<td>@forecast.Summary</td>
</tr>
}
</tbody>
</table>
}

@code {
private WeatherForecast[]? forecasts;

protected override async Task OnInitializedAsync()
{
forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
}

public class WeatherForecast
{
public DateTime Date { get; set; }

public int TemperatureC { get; set; }

public string? Summary { get; set; }

public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
@page "/"

<PageTitle>Index</PageTitle>

<h1>Hello</h1>

Welcome to multi platform Websocket client.

<p>
<a href="websocket">Example</a>
</p>
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
@page "/websocket"
@using System.Net.WebSockets
@implements IAsyncDisposable;

<h1>Websocket Example</h1>

<h3>Connecting to Bitmex server</h3>
<small>Running: @_client?.IsRunning</small>

@if (_client?.IsRunning == true)
{
<div class="sticky-top w-50 mb-3 mt-3">
<form @onsubmit="@SendMessage">

<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Message</span>
</div>
<input @bind="@_message" type="text" class="form-control">
<div class="input-group-append">
<button type="submit" class="btn btn-outline-secondary">Send</button>
</div>
</div>
</form>
</div>
}

<pre>
@foreach (var log in GetLogs())
{
var timestamp = log.Timestamp.ToLocalTime().ToString("HH:mm:ss.fff");
switch (log.Severity)
{
case LogSeverity.Warning:
<div class="text-warning">@timestamp @log.Message</div>
break;
case LogSeverity.Error:
<div class="text-danger">@timestamp @log.Message</div>
break;
default:
<div class="text-secondary">@timestamp @log.Message</div>
break;
}
}
</pre>

@code {
private readonly List<LogMessage> _logs = new();
private IWebsocketClient? _client;
private string _message = "ping";

protected override async Task OnInitializedAsync()
{
var url = new Uri("wss://www.bitmex.com/realtime");
_client = new WebsocketClient(url);

_client.Name = "Bitmex";
_client.ReconnectTimeout = TimeSpan.FromSeconds(120);
_client.ErrorReconnectTimeout = TimeSpan.FromSeconds(30);
_client.ReconnectionHappened.Subscribe(info =>
{
Console.WriteLine($"Reconnection happened, type: {info.Type}, url: {_client.Url}");
Log($"Reconnected, type: '{info.Type}'", LogSeverity.Warning);
StateHasChanged();
});
_client.DisconnectionHappened.Subscribe(info =>
{
Console.WriteLine($"Disconnection happened, type: {info.Type}");
Log($"Disconnected, type: '{info.Type}', reason: '{info.CloseStatus}'", LogSeverity.Warning);
StateHasChanged();
});

_client.MessageReceived.Subscribe(msg =>
{
Console.WriteLine($"Message received: {msg}");
Log($"Received: '{msg.Text}'", LogSeverity.Info);
StateHasChanged();
});

Console.WriteLine("Starting...");
await _client.Start();
Console.WriteLine("Started.");
}

public async ValueTask DisposeAsync()
{
if (_client == null)
return;

await _client.Stop(WebSocketCloseStatus.NormalClosure, string.Empty);
_client.Dispose();
}

private void SendMessage()
{
Log($"Sending: '{_message}'", LogSeverity.Info);
_client?.Send(_message);
}

private void Log(string message, LogSeverity severity)
{
_logs.Add(new LogMessage(message, severity, DateTime.UtcNow));
}

private LogMessage[] GetLogs() => _logs.ToArray().Reverse().ToArray();

private record LogMessage(string Message, LogSeverity Severity, DateTime Timestamp);

private enum LogSeverity
{
Info,
Warning,
Error
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Websocket.Client.Sample.Blazor;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

await builder.Build().RunAsync();
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:9850",
"sslPort": 44313
}
},
"profiles": {
"Websocket.Client.Sample.Blazor": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"applicationUrl": "https://localhost:7041;http://localhost:5041",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"inspectUri": "{wsProtocol}://{url.hostname}:{url.port}/_framework/debug/ws-proxy?browser={browserInspectUri}",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
@inherits LayoutComponentBase

<div class="page">
<div class="sidebar">
<NavMenu />
</div>

<main>
<div class="top-row px-4">
<a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a>
</div>

<article class="content px-4">
@Body
</article>
</main>
</div>
Loading

0 comments on commit a9954a3

Please sign in to comment.