Skip to content

Commit

Permalink
adding demos for chapter 16 on SignalR
Browse files Browse the repository at this point in the history
  • Loading branch information
cwoodruff committed Dec 16, 2024
1 parent 987374e commit 3bbee49
Show file tree
Hide file tree
Showing 10 changed files with 199 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/Ch16/SignalRClient/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
using Microsoft.AspNetCore.SignalR.Client;

var connection = new HubConnectionBuilder()
.WithUrl("https://localhost:5001/chathub")
.WithAutomaticReconnect([TimeSpan.Zero, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10)])
.Build();

try
{
await connection.StartAsync();
Console.WriteLine("Connection started successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Connection failed: {ex.Message}");
}

connection.On<string, string>("ReceiveMessage", (user, message) =>
{
Console.WriteLine($"{user}: {message}");
});

await connection.InvokeAsync("SendMessage", "User1", "Hello, SignalR!");

connection.Closed += async (error) =>
{
Console.WriteLine($"Connection closed. Error: {error?.Message}");
await Task.Delay(5000); // Wait before attempting to reconnect
try
{
await connection.StartAsync();
Console.WriteLine("Reconnection successful.");
}
catch (Exception ex)
{
Console.WriteLine($"Reconnection failed: {ex.Message}");
}
};
15 changes: 15 additions & 0 deletions src/Ch16/SignalRClient/SignalRClient.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="9.0.0" />
</ItemGroup>

</Project>
11 changes: 11 additions & 0 deletions src/Ch16/SignalRServerExample/ChatHub.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace SignalRServerExample;

using Microsoft.AspNetCore.SignalR;

public class ChatHub : Hub
{
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
33 changes: 33 additions & 0 deletions src/Ch16/SignalRServerExample/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using SignalRServerExample;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSignalR();

var app = builder.Build();

app.UseHttpsRedirection();

app.UseDefaultFiles();

app.UseStaticFiles();

app.UseRouting();

app.Use(async (context, next) =>
{
Console.WriteLine($"Incoming connection: {context.Request.Path}");
await next();
});

app.UseEndpoints(endpoints =>
{
endpoints.MapHub<ChatHub>("/chathub");
endpoints.MapFallback(context =>
{
context.Response.StatusCode = 404;
return context.Response.WriteAsync("Endpoint not found.");
});
});

app.Run();
23 changes: 23 additions & 0 deletions src/Ch16/SignalRServerExample/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
13 changes: 13 additions & 0 deletions src/Ch16/SignalRServerExample/SignalRServerExample.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.1.0" />
</ItemGroup>

</Project>
8 changes: 8 additions & 0 deletions src/Ch16/SignalRServerExample/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions src/Ch16/SignalRServerExample/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
35 changes: 35 additions & 0 deletions src/Ch16/SignalRServerExample/wwwroot/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<!DOCTYPE html>
<html>
<head>
<title>SignalR Test</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.0/signalr.min.js"></script>
</head>
<body>
<input type="text" id="user" placeholder="Enter your name">
<input type="text" id="message" placeholder="Enter a message">
<button onclick="sendMessage()">Send</button>

<ul id="messagesList"></ul>

<script>
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();

connection.on("ReceiveMessage", (user, message) => {
const li = document.createElement("li");
li.textContent = `${user}: ${message}`;
document.getElementById("messagesList").appendChild(li);
});

connection.start().catch(err => console.error(err.toString()));

function sendMessage() {
const user = document.getElementById("user").value;
const message = document.getElementById("message").value;
connection.invoke("SendMessage", user, message)
.catch(err => console.error(err.toString()));
}
</script>
</body>
</html>
14 changes: 14 additions & 0 deletions src/Ch16/ch16.sln
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SignalRServerExample", "SignalRServerExample\SignalRServerExample.csproj", "{D130D4A9-88F6-47D8-A409-4F64F8AD4691}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SignalRClient", "SignalRClient\SignalRClient.csproj", "{B12A3362-5795-4FEF-9FBC-102253CD6BB4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{D130D4A9-88F6-47D8-A409-4F64F8AD4691}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D130D4A9-88F6-47D8-A409-4F64F8AD4691}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D130D4A9-88F6-47D8-A409-4F64F8AD4691}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D130D4A9-88F6-47D8-A409-4F64F8AD4691}.Release|Any CPU.Build.0 = Release|Any CPU
{B12A3362-5795-4FEF-9FBC-102253CD6BB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{B12A3362-5795-4FEF-9FBC-102253CD6BB4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B12A3362-5795-4FEF-9FBC-102253CD6BB4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B12A3362-5795-4FEF-9FBC-102253CD6BB4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal

0 comments on commit 3bbee49

Please sign in to comment.