•
Real-time communication is critical in IoT applications, allowing instant data transmission between devices and servers. In .NET, three powerful protocols—MQTT, WebSocket, and SignalR—serve this purpose efficiently.
MQTT is lightweight, efficient, and designed for remote locations with devices having limited network bandwidth and power.
Consider a smart agriculture system that monitors environmental conditions (temperature, humidity, soil moisture).
Using MQTTNet in C#:
var factory = new MqttFactory(); var mqttClient = factory.CreateMqttClient(); var options = new MqttClientOptionsBuilder() .WithClientId("SensorClient01") .WithTcpServer("broker.hivemq.com", 1883) .Build(); await mqttClient.ConnectAsync(options); var message = new MqttApplicationMessageBuilder() .WithTopic("farm/sensors/temperature") .WithPayload("25.3") .WithExactlyOnceQoS() .Build(); await mqttClient.PublishAsync(message);
WebSockets enable bidirectional communication between client-server applications. Ideal for scenarios needing real-time interactive sessions.
Smart home automation systems where homeowners interact with the home interface to receive real-time updates on security cameras.
Using ASP.NET Core:
app.UseWebSockets(); app.Run(async context => { if (context.WebSockets.IsWebSocketRequest) { var websocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(websocket); } }); async Task Echo(WebSocket webSocket) { var buffer = new byte[1024 * 4]; WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); }
const socket = new WebSocket('ws://localhost:5000'); socket.onmessage = function(event) { console.log('Message received:', event.data); }; socket.onopen = function() { socket.send('Request live feed from camera 01'); };
SignalR simplifies real-time communication and is a perfect choice for dashboards, monitoring tools, and chat apps.
A logistics company dashboard that tracks delivery vehicles in real-time.
Using SignalR in ASP.NET Core:
public class VehicleHub : Hub { public async Task SendLocation(string vehicleId, double latitude, double longitude) { await Clients.All.SendAsync("ReceiveLocation", vehicleId, latitude, longitude); } }
services.AddSignalR(); app.UseEndpoints(endpoints => { endpoints.MapHub<VehicleHub>("/vehicleHub"); });
const connection = new signalR.HubConnectionBuilder() .withUrl("/vehicleHub") .build(); connection.on("ReceiveLocation", (vehicleId, lat, lng) => { console.log(`Vehicle ${vehicleId} is at latitude ${lat}, longitude ${lng}`); }); connection.start().then(() => { console.log('Connected to vehicle tracking hub.'); });
Leveraging MQTT, WebSocket, and SignalR in .NET empowers developers to implement robust, scalable, and efficient real-time IoT solutions, seamlessly integrating diverse scenarios into unified management systems.
0 comments
Discover the latest insights and trends from our blog.
Sustainable living involves making intentional choices to preserve natural resources, reduce pollution, and support long-term ecological balance through practices like ...
Poor software architecture leads to 5deep, hard-to-fix bugs. This article explores causes, examples, and best practices to build scalable, maintainable, bug-resistant systems. ...
Explore key software design principles like SOLID, DRY, KISS, and design patterns to build clean, scalable, and maintainable applications. Perfect for modern developers. ...