You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
2.4 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using Sln.Iot.Business;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace Sln.Iot.Business
{
/// <summary>
/// TCP服务端
/// </summary>
public class TouchTcpServer
{
private static readonly Lazy<TouchTcpServer> lazy = new Lazy<TouchTcpServer>(() => new TouchTcpServer());
public static TouchTcpServer Instance
{
get
{
return lazy.Value;
}
}
/// <summary>
/// 服务端启动
/// </summary>
public async void TcpServerStarted(string ipHost)
{
var service = new TcpService();
service.Connecting = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在连接
service.Connected = (client, e) => { return EasyTask.CompletedTask; };//有客户端成功连接
service.Closing = (client, e) => { return EasyTask.CompletedTask; };//有客户端正在断开连接,只有当主动断开时才有效。
service.Closed = (client, e) => { return EasyTask.CompletedTask; };//有客户端断开连接
#region Tcp服务器使用Received异步委托接收数据
service.Received = async (client, e) =>
{
//从客户端收到信息
var mes = e.Memory.Span.ToString(Encoding.UTF8);
client.Logger.Info($"已从{client.Id}接收到信息:{mes}");
TCPRFIDBinding.GetNewMessage?.Invoke(mes);
//简单消除Task当使用插件接收时需要使用 await e.InvokeNext();来继续执行后续插件。
await EasyTask.CompletedTask;
};
#endregion
await service.SetupAsync(new TouchSocketConfig()//载入配置
.SetListenIPHosts($"tcp://{ipHost}")//可以同时监听多个地址
.ConfigureContainer(a =>//容器的配置
{
a.AddConsoleLogger();//添加一个控制台日志注入注意在maui中控制台日志不可用
})
.ConfigurePlugins(a =>
{
//a.Add();//此处可以添加插件
}));
await service.StartAsync();//启动
}
}
}