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.

70 lines
2.5 KiB
C#

using Microsoft.Extensions.Logging;
using System;
using System.Text;
using TouchSocket.Core;
using TouchSocket.Sockets;
namespace SlnMesnac.TouchSocket
{
public class TcpServer
{
private ILogger<TcpServer> _logger;
private readonly TcpService _service;
public TcpServer(ILogger<TcpServer> logger,TcpService tcpService)
{
_logger = logger;
_service = tcpService;
}
public void Init(int serverPort)
{
try
{
11 months ago
_service.Connecting = (client, e) => {
_logger.LogInformation($"客户端{client.IP}正在接入服务");
return EasyTask.CompletedTask;
};
11 months ago
_service.Connected = (client, e) => {
_logger.LogInformation($"客户端{client.IP}接入服务成功");
return EasyTask.CompletedTask;
};
11 months ago
_service.Disconnected = (client, e) => {
_logger.LogInformation($"客户端{client.IP}断开连接");
return EasyTask.CompletedTask;
};
_service.Received = (client, e) =>
{
//if (requestInfo is MyFixedHeaderRequestInfo myRequestInfo)
//{
// string body = Encoding.UTF8.GetString(myRequestInfo.Body, 0, myRequestInfo.Body.Length);
//}
//从客户端收到信息
var mes = Encoding.UTF8.GetString(e.ByteBlock.Buffer, 0, e.ByteBlock.Len);//注意数据长度是byteBlock.Len
return EasyTask.CompletedTask;
};
_service.Setup(new TouchSocketConfig()//载入配置
.SetListenIPHosts(new IPHost[] { new IPHost($"0.0.0.0:{serverPort}") })
.ConfigureContainer(a =>//容器的配置顺序应该在最前面
{
11 months ago
a.AddConsoleLogger();
})
.ConfigurePlugins(a =>
{
11 months ago
//自定义插件
}));
_service.Start();
_logger.LogInformation($"TcpServer启动成功监听端口{serverPort}");
}
catch (Exception ex)
{
11 months ago
_logger.LogError($"TcpServer启动异常{ex}");
throw new Exception(ex.Message);
}
}
}
}