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

167 lines
4.8 KiB

6 months ago
using System.Reflection;
using Autofac;
using Autofac.Core;
using DotNetty.Codecs;
using DotNetty.Common.Internal.Logging;
using DotNetty.Handlers.Logging;
6 months ago
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using HybirdFrameworkCore.Autofac;
using HybirdFrameworkCore.Autofac.Attribute;
using log4net;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using LogLevel = DotNetty.Handlers.Logging.LogLevel;
6 months ago
namespace HybirdFrameworkDriver.TcpClient;
public class TcpClient<TH, TD, TE> : IDisposable where TH : IChannelHandler
6 months ago
where TD : ByteToMessageDecoder, new()
where TE : ChannelHandlerAdapter, new()
6 months ago
{
[JsonIgnore]
6 months ago
private static readonly ILog Log = LogManager.GetLogger(typeof(TcpClient<TH, TD, TE>));
[JsonIgnore]
6 months ago
private Bootstrap? _bootstrap;
[JsonIgnore]
private IEventLoopGroup? _eventLoopGroup;
[JsonIgnore]
public IChannel? Channel { get; set; }
6 months ago
6 months ago
public bool Connected { get; set; }
6 months ago
6 months ago
public string Host { get; set; }
public int Port { get; set; }
public bool AutoReconnect { get; set; }
public LogLevel? LogLevel { get; set; }
6 months ago
6 months ago
public void InitBootstrap(string host, int port, Action? channelInactiveHandler = null)
6 months ago
{
Host = host;
Port = port;
if (LogLevel != null)
{
InternalLoggerFactory.DefaultFactory.AddProvider(new Log4NetProvider());
}
6 months ago
_bootstrap = new Bootstrap();
_eventLoopGroup = new MultithreadEventLoopGroup();
6 months ago
_bootstrap
.Group(_eventLoopGroup)
6 months ago
.Channel<TcpSocketChannel>()
.Option(ChannelOption.TcpNodelay, true)
.Handler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
var clientListenerHandler = new ClientListenerHandler<TH, TD, TE>(this, AutoReconnect);
6 months ago
6 months ago
var pipeline = channel.Pipeline;
if (LogLevel != null)
{
pipeline.AddLast(new LoggingHandler(LogLevel.Value));
}
6 months ago
// 监听器
pipeline.AddLast(clientListenerHandler);
pipeline.AddLast("idleStateHandler", new IdleStateHandler(30, 0, 0)); // 触发读取超时
// 可以添加编解码器等
ResolveDecode(pipeline);
ResolveEncode(pipeline);
ResolveHandler(pipeline);
}));
}
private void ResolveEncode(IChannelPipeline pipeline)
{
pipeline.AddLast(new TE());
}
private void ResolveDecode(IChannelPipeline pipeline)
{
pipeline.AddLast(new TD());
}
private void ResolveHandler(IChannelPipeline pipeline)
{
6 months ago
var list = new List<Type>();
6 months ago
6 months ago
foreach (var reg in AppInfo.Container.ComponentRegistry.Registrations)
foreach (var service in reg.Services)
if (service is TypedService ts)
if (MatchHandlers(ts))
list.Add(ts.ServiceType);
6 months ago
6 months ago
var handlers = new List<TH>();
6 months ago
foreach (var type in list)
{
6 months ago
var resolve = AppInfo.Container.Resolve(type);
6 months ago
handlers.Add((TH)resolve);
6 months ago
}
6 months ago
6 months ago
handlers.Sort((handler, msgHandler) =>
{
6 months ago
var orderAttribute1 = handler.GetType().GetCustomAttribute<OrderAttribute>();
var orderAttribute2 = msgHandler.GetType().GetCustomAttribute<OrderAttribute>();
var h1Order = orderAttribute1?.Order ?? 0;
var h2Order = orderAttribute2?.Order ?? 0;
6 months ago
return h1Order.CompareTo(h2Order);
});
6 months ago
foreach (var msgHandler in handlers) pipeline.AddLast(msgHandler);
6 months ago
}
private bool MatchHandlers(TypedService ts)
{
6 months ago
var interfaces = ts.ServiceType.GetInterfaces();
6 months ago
if (interfaces.Length > 0)
6 months ago
foreach (var type in interfaces)
6 months ago
if (type == typeof(TH))
return true;
return false;
}
public void BaseConnect()
6 months ago
{
Connected = false;
6 months ago
Log.Info($"begin to connect {Host}:{Port}");
6 months ago
6 months ago
while (!Connected)
6 months ago
{
try
{
Task<IChannel> task = _bootstrap!.ConnectAsync(Host, Port);
6 months ago
Channel = task.Result;
Connected = Channel.Open;
}
catch (Exception e)
6 months ago
{
6 months ago
Log.Info($"connect {Host}:{Port} {e}");
6 months ago
}
6 months ago
Log.Info($"connect {Host}:{Port} {Connected}");
Thread.Sleep(1000);
6 months ago
}
}
public void Close()
{
this.Channel?.CloseAsync().Wait();
this.Channel?.CloseCompletion.Wait();
_eventLoopGroup?.ShutdownGracefullyAsync().Wait();
}
public void Dispose()
{
this.Close();
this.Connected = false;
}
6 months ago
}