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
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
Startup.cs
WebSocketSharp, which has anOnMessagefeature. Reference