FubarDevelopment / FtpServer

Portable FTP server written in .NET
http://fubardevelopment.github.io/FtpServer/
MIT License
482 stars 163 forks source link

How to subscribe the FtpConnectionDataTransferStartedEvent & FtpConnectionDataTransferStoppedEvent event? #120

Closed weiluenju closed 3 years ago

weiluenju commented 3 years ago

I am a beginner.

How to subscribe the FtpConnectionDataTransferStartedEvent & FtpConnectionDataTransferStoppedEvent event or how to use?

There is my code:

ServiceCollection services = new ServiceCollection();
services.AddFtpServer(builder => {
    builder.UseDotNetFileSystem();
});

services.AddSingleton<IMembershipProvider, MyMembershipProvider>();
services.AddSingleton<IAccountDirectoryQuery, MyAccountDirectoryQuery>();

services.Configure<DotNetFileSystemOptions>(opt =>
    opt.RootPath = ftpRoot
);

services.Configure<FtpServerOptions>(opt => {
    opt.Port = port;
});

services.Configure<SimplePasvOptions>(opt => {
    opt.PasvMinPort = 7000;
    opt.PasvMaxPort = 7100;
});

ServiceProvider serviceProvider = services.BuildServiceProvider();
ftpServerHost = serviceProvider.GetRequiredService<IFtpServerHost>();
ftpServerHost.StartAsync(CancellationToken.None).Wait();

Thank you.

fubar-coder commented 3 years ago

The IFtpConnection implementation also implements IObservable<IFtpConnectionEvent>, but you have to register your observer for all connections.

First, you have to create an implementation of IFtpConnectionConfigurator. An example for this interface is the class AuthTlsConfigurator, which is used to implement implicit TLS. Your implementation has to be registered as (singleton!) service too.

Now, you can subscribe the connection events.

if (connection is IObservable<IFtpConnectionEvent> observable)
{
  _subscription = observable.Subscribe(new YourEventObserver());
}

The class YourEventObserver must implement IObserver<IFtpConnectionEvent>. In the OnNext function, you get a IFtpConnectionEvent parameter. FtpConnectionDataTransferStartedEvent implements this interface and can be tested fir with pattern matching.

An example for an event observer can be found in the class FtpConnectionIdleCheck.

weiluenju commented 3 years ago

I follow your teaching and successfully subscribe the events.

Thank you very much.