使用C#开发服务器端程序

WebAPI.Client 中提供接收服务器与设备之间的网络传输数据,该功能由Asp.Net Core SignalR技术开发。


使用WebAPI.Client 开发服务器端Console Application。
  1. 使用Visual Studio 2022 开发软件,新建 Console Application 项目
  2. 添加项目引用:IoT.API.WebApi.Client.dll
  3. 找到Program.cs,在Main方法中添加以下代码:
    using System;
    using System.Threading.Tasks;
    using System.Threading;
    using Newtonsoft.Json;
    using IoT.API.WebApi.Client;
    
    namespace IoT.Example.ConsoleApp
    {
        internal class Program
        {
            public static CancellationTokenSource _cancellationTokenSource = null;
            static void Main(string[] args)
            {
                Console.WriteLine("Initializing...");
                AppClient.GetInstance().Initialize("9b90ddc743c44125a67f0f847749b19c", "User-3", "NGY5OTAwMzRkNWZlNDI4MzgzZDc0ODBkZGQwZDEzNmM=");
    
                Console.WriteLine("Starting...");
                var terminal = AppClient.GetInstance().PhysicalManager;
                terminal.Connect();
                terminal.OnReceiveMessage += (obj) => {
                    Console.WriteLine(obj);
                };
                Console.WriteLine("Has started");
                
                _cancellationTokenSource = new CancellationTokenSource();
                Task.Run(async () => {
                    while (!_cancellationTokenSource.IsCancellationRequested)
                    {
                        terminal.Send("Get", AppClient.GetInstance().GetToken(), "869627031275308");
                        await Task.Delay(1000);
                    }
                });
    
                Console.WriteLine("");
                Console.WriteLine("Press key 'q' to stop the Service.");
                Console.WriteLine("-------------------------------------------------------------------");
                while (Console.ReadKey().Key != ConsoleKey.Q)
                {
                    Console.WriteLine("");
                    continue;
                }
    
                _cancellationTokenSource.Cancel();
    
                Console.WriteLine("");
                Console.WriteLine("The Service has been stopped!");
            }
    
        }
    }
    
                        
  4. 完成以上操作,就可以在程序中使用AppClient.GetInstance().PhysicalManager 中方法调用数据。详细请参考示例程序。



下载 Console 示例程序

示例程序,运行环境要求为 .Net Core 5

  1. Example Source Code:https://cloud.tzonedigital.cn/f/dev/Example.ConsoleApp/source_code.zip