// 定义 public abstract class AbstractBootstrap<TBootstrap, TChannel> where TBootstrap : AbstractBootstrap<TBootstrap, TChannel> where TChannel : IChannel // 定义子类 public class Bootstrap : AbstractBootstrap<Bootstrap, IChannel> // 方法实现 public virtual TBootstrap Group(IEventLoopGroup group) { Contract.Requires(group != null);
if (this.group != null) { throw new InvalidOperationException("group has already been set."); } this.group = group; return (TBootstrap)this; } // 使用 var bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel<TcpSocketChannel>() .Handler(new ActionChannelInitializer<ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new EchoClientHandler()); }));
API
客户端引导
1 2 3 4 5 6 7 8 9 10 11 12 13
var group = new MultithreadEventLoopGroup(); var bootstrap = new Bootstrap(); bootstrap .Group(group) .Channel<TcpSocketChannel>() .Handler(new ActionChannelInitializer<ISocketChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new EchoClientHandler()); })); IChannel clientChannel = await bootstrap.ConnectAsync(new IPEndPoint(IPAddress.Parse("10.10.10.158"), 3000)); Console.ReadLine(); await clientChannel.CloseAsync();