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.

79 lines
2.8 KiB

using DotNetty.Buffers;
8 months ago
using DotNetty.Handlers.Logging;
using DotNetty.Handlers.Timeout;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using HybirdFrameworkCore.Autofac.Attribute;
8 months ago
using log4net;
namespace HybirdFrameworkServices.Netty
{
/// <summary>
/// netty server
/// </summary>
[Scope("SingleInstance")]
8 months ago
public class Server : IDisposable
{
private readonly ILog Log = LogManager.GetLogger(typeof(Server));
static MultithreadEventLoopGroup? bossGroup;
static MultithreadEventLoopGroup? workerGroup;
static ServerBootstrap? bootstrap;
private int _port = 9000;
8 months ago
public void connect(int port)
8 months ago
{
_port = port;
IByteBuffer delimiter = Unpooled.CopiedBuffer(new byte[] { 0xAA, 0xF5 });
8 months ago
bossGroup = new MultithreadEventLoopGroup();
workerGroup = new MultithreadEventLoopGroup();
bootstrap = new ServerBootstrap();
bootstrap
.Group(bossGroup, workerGroup) // 设置主和工作线程组
.Channel<TcpServerSocketChannel>() // 设置通道模式为TcpSocket
.Option(ChannelOption.SoKeepalive, true) //保持连接
.Handler(new LoggingHandler())
.ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
{
var serverListenerHandler = new ServerListenerHandler();
IChannelPipeline pipeline = channel.Pipeline;
pipeline.AddLast(new LoggingHandler(""));
pipeline.AddLast(serverListenerHandler);
//pipeline.AddLast(new FixedLengthFrameDecoder(12)); //定长数据12byte
pipeline.AddLast(new IdleStateHandler(0, 0, 180));//检测空闲连接
//pipeline.AddLast(msgHandler);
//业务handler 这里是实际处理业务的Handler
pipeline.AddLast(new Decoder());
pipeline.AddLast(new Encoder());
pipeline.AddLast(new MsgHandler());
8 months ago
}));
Begin(_port);
}
public void Begin(int port)
8 months ago
{
_port = port;
Log.Info(" Start Listen");
Task<IChannel>? channel = bootstrap?.BindAsync(_port);
Log.Info($"netty success listen {_port}");
}
/// <summary>
/// ??netty
/// </summary>
public void Dispose()
{
Log.Info(this + " Dispose");
bossGroup?.ShutdownGracefullyAsync();
}
}
}