1
0
Fork 0
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.

59 lines
2.0 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace HighWayIot.TouchSocket
{
public class TouchSocketTcpServer
{
private static readonly Lazy<TouchSocketTcpServer> lazy = new Lazy<TouchSocketTcpServer>(() => new TouchSocketTcpServer());
public static TouchSocketTcpServer Instance => lazy.Value;
TcpService service = new TcpService();
public async void TcpServer()
{
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;
};//有客户端断开连接
service.Received = async (client, e) =>
{
//从客户端收到信息
var mes = e.ByteBlock.Span.ToString(Encoding.UTF8);
client.Logger.Info($"已从{client.Id}接收到信息:{mes}");
};
await service.SetupAsync(new TouchSocketConfig()//载入配置
.SetListenIPHosts("tcp://127.0.0.1:7789", 7790)//可以同时监听两个地址
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
{
a.AddConsoleLogger();//添加一个控制台日志注入注意在maui中控制台日志不可用
})
.ConfigurePlugins(a =>
{
//a.Add();//此处可以添加插件
}));
await service.StartAsync();//启动
}
}
}