KD2ND
KD2ND

Reputation: 321

azure Web PubSub Service. event handler for incoming client messages

Using Azure web pubsub service. We use .net framework 4.8 (not .net CORE). Trying to subscribe to incoming messages from clients.

Following is our service code (simplified):

using Azure.Messaging.WebPubSub;
using System;
using System.Threading.Tasks;

namespace pubsubservice
{
    internal class Program
    {
        private const string cs = "Endpoint=https://mypubsub.webpubsub.azure.com;AccessKey=MyKey;Version=1.0;";
        private const string hub = "Hub";
        static void Main(string[] args)
        {
            var serviceClient = new
            WebPubSubServiceClient(cs, hub);

            Console.WriteLine("Server is running...");

            serviceClient.SendToAll("Hello");

            Console.WriteLine("\n Server - Type 'exit' to exit.\n");
            var msg = Console.ReadLine();

        }

    }
}

The service works as expected.

This is my pubsub client tester :

using System;
using System.Net.WebSockets;
using System.Threading;
using System.Threading.Tasks;

namespace PubsubClient
{
    internal class Program
    {
        private static string url = "wss://mypubsub.webpubsub.azure.com/client/hubs/Hub?access_token=MyToken";

        private static object consoleLock = new object();
        private const int sendChunkSize = 256;
        private const int receiveChunkSize = 64;
        private const bool verbose = true;
        private static readonly TimeSpan delay = TimeSpan.FromMilliseconds(1000);

        static void Main(string[] args)
        {
            Thread.Sleep(1000);
            Connect(url).Wait();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        public static async Task Connect(string uri)
        {
            ClientWebSocket webSocket = null;

            try
            {
                webSocket = new ClientWebSocket();
                await webSocket.ConnectAsync(new Uri(uri), CancellationToken.None);
                await Task.WhenAll(Receive(webSocket), Send(webSocket));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: {0}", ex);
            }
            finally
            {
                if (webSocket != null)
                    webSocket.Dispose();
                Console.WriteLine();

                lock (consoleLock)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("WebSocket closed.");
                    Console.ResetColor();
                }
            }
        }

        private static async Task Send(ClientWebSocket webSocket)
        {
            var random = new Random();
            byte[] buffer = new byte[sendChunkSize];

            while (webSocket.State == WebSocketState.Open)
            {
                random.NextBytes(buffer);

                await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Binary, false, CancellationToken.None);
                LogStatus(false, buffer, buffer.Length);

                await Task.Delay(delay);
            }
        }

        private static async Task Receive(ClientWebSocket webSocket)
        {
            byte[] buffer = new byte[receiveChunkSize];
            while (webSocket.State == WebSocketState.Open)
            {
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
                if (result.MessageType == WebSocketMessageType.Close)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
                }
                else
                {
                    LogStatus(true, buffer, result.Count);
                }
            }
        }

        private static void LogStatus(bool receiving, byte[] buffer, int length)
        {
            lock (consoleLock)
            {
                Console.ForegroundColor = receiving ? ConsoleColor.Green : ConsoleColor.Gray;
                Console.WriteLine("{0} {1} bytes... ", receiving ? "Received" : "Sent", length);

                if (verbose)
                    Console.WriteLine(BitConverter.ToString(buffer, 0, length));

                Console.ResetColor();
            }
        }
    }
}

The websocket is established successfully , the client sends and receive data.

My question is how do I handle the sent data in the server? Is there an event (e.g. OnMessage, OnMessageReceived)? The client seems to send the message but I cannot figure how to handle it in the server.

Thanks

Upvotes: 0

Views: 357

Answers (1)

Sampath
Sampath

Reputation: 3533

I followed the code that creates a WebSocket connection and allows the user to send and receive messages.

I followed the process of setting up WebSockets with .NET in an App Service, both for Windows and Linux plans, using onmessage.

index.html


  sendButton.onclick = function () {
            if (!socket || socket.readyState !== WebSocket.OPEN) {
                alert("socket not connected");
            }
            var data = sendMessage.value;
            socket.send(data);
            commsLog.innerHTML += '<tr>' +
                '<td class="commslog-client">Client</td>' +
                '<td class="commslog-server">Server</td>' +
                '<td class="commslog-data">' + htmlEscape(data) + '</td></tr>';
        };

        connectButton.onclick = function() {
            stateLabel.innerHTML = "Connecting";
            socket = new WebSocket(connectionUrl.value);
            socket.onopen = function (event) {
                updateState();
                commsLog.innerHTML += '<tr>' +
                    '<td colspan="3" class="commslog-data">Connection opened</td>' +
                '</tr>';
            };
            socket.onclose = function (event) {
                updateState();
                commsLog.innerHTML += '<tr>' +
                    '<td colspan="3" class="commslog-data">Connection closed. Code: ' + htmlEscape(event.code) + '. Reason: ' + htmlEscape(event.reason) + '</td>' +
                '</tr>';
            };
            socket.onerror = updateState;
            socket.onmessage = function (event) {
                commsLog.innerHTML += '<tr>' +
                    '<td class="commslog-server">Server</td>' +
                    '<td class="commslog-client">Client</td>' +
                    '<td class="commslog-data">' + htmlEscape(event.data) + '</td></tr>';
            };
        };

Startup.cs


var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();

var app = builder.Build();

// <snippet_UseWebSockets>
var webSocketOptions = new WebSocketOptions
{
    KeepAliveInterval = TimeSpan.FromMinutes(2)
};

app.UseWebSockets(webSocketOptions);
// </snippet_UseWebSockets>

app.UseDefaultFiles();
app.UseStaticFiles();

app.MapControllers();

app.Run();




enter image description here

  • Another option is to use WebSocketSharp, which has an OnMessage feature. Reference

Upvotes: 0

Related Questions