chronoxor / NetCoreServer

Ultra fast and low latency asynchronous socket server & client C# .NET Core library with support TCP, SSL, UDP, HTTP, HTTPS, WebSocket protocols and 10K connections problem solution
https://chronoxor.github.io/NetCoreServer
MIT License
2.63k stars 550 forks source link

Call a scoped service method inside OnReceived #198

Open samnemo94 opened 2 years ago

samnemo94 commented 2 years ago

Consider the "TCP chat server" example; inside OnReceived method: I want to call an async method of a scoped service. So I have two questions: 1- How can I pass the scoped service to the OnReceived ? is it a proper way to pass it to ChatServer constructor and then to ChatSession constructor? 2- How can I make the OnReceived method async because the method I want to invoke is async? Use Case: I'm implementing two micro-services, one is the socket server that listens to a port and invokes RPC method from another service so the RPC invocation requires async.

CwjXFH commented 1 year ago

Inject a ServiceProvider into your WsSession,then you can create a scope service when you need it.

About invoke OnReceived async, I do like this:

public override async void OnWsReceived(byte[] buffer, long offset, long size)
{
    try
    {
        await DoAsync(CancellationToken.None)
    }
    catch (Exception ex)
    {
        _logger.LogError(ex);
    }
}

private async Task DoAsync(CancellationToken cancellationToken)
{
    // ...
}

Maybe this issue can also help you about invoke OnReceived async