Signal R

Real-time, two way, server and client communication

Updated: 03 September 2023

Microsoft Documentation

Signal R is a way to add real-time functionality to a .NET Web API, it makes use of a Server and Client side connection enabling two way transfer of data between them

Setting Up

This post assumes some base knowledge on .NET Core Web Applications as well as React and Typescript

Create the Projects

  1. Create a new directory for the project
Terminal window
1
mkdir SignalRTypeScript
  1. Create a new .NET Web App and add it to the solution
Terminal window
1
dotnet new web -o Server
2
dotnet sln ./SignalRTypescript.sln add ./Server
  1. Create a new React App with Typescript for the frontend
Terminal window
1
yarn create react-app web --template typescript

Configure Server

On the Server application we need to:

  1. Create a new class for our communication Hub

Inside of this class we can add a function that will allow us to receive a message and broadcast that message to all connected clients:

Server/Hubs/MessageHub.cs

1
using Microsoft.AspNetCore.SignalR;
2
3
namespace Server.Hubs
4
{
5
public class MessageHub : Hub
6
{
7
public async Task NewMessage(string username, string message)
8
{
9
await Clients.All.SendAsync("messageReceived", username, message);
10
}
11
}
12
}
  1. Add SignalR to the ConfigureServices method as well as AddCors so that our client can connect to our server

Startup.cs

1
public void ConfigureServices(IServiceCollection services)
2
{
3
services.AddCors();
4
services.AddSignalR();
5
}
  1. Add the Hub mapping on the Configure method to the app.UseEndpoints lambda and the Cors rule we want to apply

startup.cs

1
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
2
{
3
//... existing default code not shown
4
5
app.UseCors(
6
options => options.WithOrigins("http://localhost:3000")
7
.AllowAnyMethod()
8
.AllowAnyHeader()
9
.AllowCredentials()
10
);
11
12
app.UseEndpoints(endpoints =>
13
{
14
endpoints.MapHub<MessageHub>("/hub");
15
});
16
}
  1. Lastly we will need to either check what port our application is running on, or more simply set the port using Visual Studio or the dotnet cli when you run the application

Configure the Client

  1. On the Client application (web) we need to install the SignalR packages so that we can consume the SignalR Client library
Terminal window
1
yarn add @microsoft/signalr

We will make use of two React components in our application, the App component will be the main application component and will handle the dispatching of messages to the server, and the MessageViewer component which will handle subscribing to and displaying the messages broadcasted by the server

  1. Create the MessageViewer component:

MessageViewer.tsx

1
import React, { Component } from 'react'
2
import { HubConnectionBuilder, HubConnection } from '@microsoft/signalr'
3
import './App.css'
4
5
type Message = {
6
message: string
7
username: string
8
}
9
10
type MessageViewerState = {
11
messages: Message[]
12
connection: HubConnection
13
}
14
15
class MessageViewer extends Component<{}, MessageViewerState> {
16
render() {
17
return (
18
<div className="MessageViewer">
19
{this.state.messages.map((m) => m.message).join(' ')}
20
</div>
21
)
22
}
23
}
24
25
export default MessageViewer

So far we have just implemented the render method for the component and the relevant types, however we need to implement the constructor to initialize our properties, and the componentDidMount and messageHandler methods so we set up the connection to the Server and handle the messages sent from it. In the class definition for the MessageViewerComponent included those functions:

In the constructor we just initialize our state with an empty message array and the HubConnection. The Hub Connection is built using the HubConnectionBuilder

MessageViewer.tsx

1
constructor(props: any) {
2
super(props)
3
4
this.state = {
5
messages: [],
6
connection: new HubConnectionBuilder().withUrl("http://localhost:4000/hub").build()
7
}
8
}

Then we will define an async componentDidMount method in which we will start the server connection as well as set up which messages we would like to subscribe and respond to:

MessageViewer.tsx

1
async componentDidMount() {
2
3
try {
4
// start connection
5
await this.state.connection.start()
6
console.log('connection started')
7
} catch (error) {
8
console.error(error)
9
}
10
11
// subscribe to the `messageReceived` event
12
this.state.connection.on('messageReceived', this.handleMessage)
13
}

And then define the handleMessage function which will update our state based on the messages we receive:

MessageViewer.tsx

1
handleMessage = (username: string, message: string) =>
2
this.setState({
3
...this.state,
4
messages: [...this.state.messages, { message, username }],
5
})
Complete `MessageViewer.tsx` file
1
import React, { Component } from 'react'
2
import { HubConnectionBuilder, HubConnection } from '@microsoft/signalr'
3
import './App.css'
4
5
type Message = {
6
message: string
7
username: string
8
}
9
10
type MessageViewerState = {
11
messages: Message[]
12
connection: HubConnection
13
}
14
15
class MessageViewer extends Component<{}, MessageViewerState> {
16
constructor(props: any) {
17
super(props)
18
19
this.state = {
20
messages: [],
21
connection: new HubConnectionBuilder()
22
.withUrl('http://localhost:4000/hub')
23
.build(),
24
}
25
}
26
27
handleMessage = (username: string, message: string) =>
28
this.setState({
29
...this.state,
30
messages: [...this.state.messages, { message, username }],
31
})
32
33
async componentDidMount() {
34
try {
35
await this.state.connection.start()
36
console.log('connection started')
37
} catch (error) {
38
console.error(error)
39
}
40
41
this.state.connection.on('messageReceived', this.handleMessage)
42
}
43
44
render() {
45
return (
46
<div className="MessageViewer">
47
{this.state.messages.map((m) => m.message).join(' ')}
48
</div>
49
)
50
}
51
}
52
53
export default MessageViewer
  1. Create the App component

For our initial connection configuration we will use some of the same code we used in the MessageViewer component, the App.tsx file will however additionally send messages to the SignalR Hub, for our purpose a new message will be sent each time the user presses a key on the keyboard. Initially the App.tsx file contains the following basic content:

App.tsx

1
import React, { Component } from 'react'
2
import './App.css'
3
import { HubConnectionBuilder, HubConnection } from '@microsoft/signalr'
4
import MessageViewer from './MessageViewer'
5
6
type AppState = {
7
connectionUser: string
8
connection: HubConnection
9
}
10
11
class App extends Component<{}, AppState> {
12
constructor(props: any) {
13
super(props)
14
15
this.state = {
16
connectionUser: 'App',
17
connection: new HubConnectionBuilder()
18
.withUrl('http://localhost:4000/hub')
19
.build(),
20
}
21
}
22
23
render() {
24
return (
25
<div className="App">
26
<MessageViewer />
27
</div>
28
)
29
}
30
}
31
32
export default App

Next, we need to add some functionality to the component. First, in the async componentDidMount function we will connect to the server and and add an event listener for keydown events, and a componentWillUnmount which will remove the listener when the component unmounts:

App.tsx

1
async componentDidMount() {
2
try {
3
await this.state.connection.start()
4
console.log('connection started')
5
} catch (error) {
6
console.error(error)
7
}
8
9
document.addEventListener('keydown', this.handleKeydown)
10
}
11
12
componentWillUnmount() {
13
document.removeEventListener('keydown', this.handleKeydown)
14
}

Lastly we can add the handleKeydown function on our component to send a message each time the keydown event is triggered

App.tsx

1
handleKeydown = async (e: KeyboardEvent) => {
2
try {
3
await this.state.connection.send(
4
'newMessage',
5
this.state.connectionUser,
6
e.key
7
)
8
} catch (error) {
9
console.error(error)
10
}
11
}

You should be able to now run your Server and Web applications using dotnet and yarn (or npm) respectively and when clicking any key on your keyboard it should appear on the screen. This will be displayed in the MessageViewer component which is subscribed to the events