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.
- 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)
4. Create a new folder under WebSocketApp called Middleware.
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.
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.
11. Post a message to http://localhost:5000/message and you will see the message in your browser instantly.
Till next time!