WebSockets with Giraffe and F#

The age of polling a server to get data is long gone but I still see it on the web from time to time and it really annoys me. In this post I’ll give you the steps to get up and running with WebSockets quickly. Stop wasting resources, remove polling and enjoy the awesomeness of WebSockets. Lets go!

As in the previous posts I’ll be using VSCode with Ionide and dotnet-cli version 2.1.3. This post will be using the new Giraffe template so please update with dotnet new -i "giraffe-template::*" before creating a new project to avoid any confusion.

  1. Create a new Giraffe project.
dotnet new giraffe --ViewEngine razor -o WebSocketApp

2. Add Microsoft.AspNetCore.WebSockets to the project.

dotnet add package Microsoft.AspNetCore.WebSockets

3. Build the project (to enable code completion in VSCode)

dotnet build

4. Create a new folder under WebSocketApp called Middleware.

Image for post
Image for post

5. Create a file called WebSocketMiddleware.fs and enter the following code:

6. Add the WebSocketMiddleware.fs file to the .fsproj project file.

7. Add .UseWebSockets and .UseMiddleware to configureApp in Program.fs.

8. Add the missing references under WebSocketApp.Models in Program.fs.

open WebSocketApp.Models
open WebSocketApp.Middleware
open Microsoft.AspNetCore.Http

9. Open Views\Index.cshtml and add the following below the existing code:

10. To be able to send messages to connected clients add a new endpoint above webApp and add a new route. This endpoint will send the received message to all connected WebSocket clients.

10. Run the application and visit http://localhost:5000.

dotnet run
Image for post
Image for post

11. Post a message to http://localhost:5000/message and you will see the message in your browser instantly.

Image for post
Image for post
Image for post
Image for post

Till next time!

Written by

Software Architect/Developer .NET/ASP.NET. Architecture, software and webdev geek. Go gopher, Rustacean and F# connoisseur. Master of Digital Wizardry.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store