WebSocketNotify
WebSocketNotify is a dotnet-core package available on github.com and nuget.org to work with WebSocket standard in your website.
How it works?
It is a very lightweight ClassLibrary built for dotnet core 3.1 and later that uses DI(dependency injection) to register WSNotifyHandler
, Options Pattern and IOptionMonitor
to carry out options for WSNotifyHandler
and Extension Methods to append itself into dotnet core pipeline.
How to use it?
Although there is a sample of asp.net core project available on github.com , here is a step-by-step tutorial to show you how to use WSNotify package into your own project.
Server side
To enable your website to accept WebSocket requests and receive message from clients or send/broadcast message to clients, you need to follow these steps:
- You need to add hShahpouri.WebSocketNotify package to your project. It is available on github.com and nuget.org
- Create your desired options into appsettings.json file like these default settings:
"WSNotify": { "Route": "/ws", "ConnectionPerIP": 1 }
- Append this line into
ConfigureServices()
method in Startup.cs// using WebSocketNotify; public void ConfigureServices(IServiceCollection services) { ... services.AddWebSocketNotify(Configuration); ... }
- Prepend this line into
Configure()
method in Startup.cspublic void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // this code should be placed at the most first line of method's body or // immediately after your error handling middleware, for example: // app.UseDeveloperExceptionPage(); app.UseWebSocketNotify(); ... }
- Now you need to get
WSNotifyHandler
service from ServiceCollection using DI and register a delegate for receiving messages from clients. The best place for doing it is in Program.cs file, such as below:public class Program { public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); RegisterReceiver(host); host.Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); // Use this method to register a delegate to handle all received messages private static void RegisterReceiver(IHost host) { var handler = host.Services.GetRequiredService<WSNotifyHandler>(); handler.OnReceive += (key, value, type) => { Console.WriteLine(); Console.WriteLine("--------------------------------[BEGIN]"); Console.WriteLine($"({type}) from {key}"); Console.WriteLine(value); Console.WriteLine("--------------------------------[END]"); Console.WriteLine(); }; } }
- Wherever you want to send a message to clients you just need to get
WSNotifyHandler
service using DI and then callSendAsync()
method.
Client side
To start communicating with server using WebSocket, you need to follow these steps:
- In your webpage, inside a
<script>
tag (or a .js file) add this block:/** @type{WebSocket} */ var ws = null; function socket_connect() { ws = new WebSocket("wss://localhost:5001/ws"); ws.onopen = function (ev) { console.log("onopen", ev); }; ws.onerror = function (ev) { console.log("onerror", ev); }; ws.onclose = function (ev) { console.log("onclose", ev); }; ws.onmessage = function (ev) { console.log("onmessage", ev.data); }; } function socket_close() { ws.close(); } function socket_send() { ws.send("this is a message from client to server over WebSocket"); }
For more details see Writing WebSocket client applications.