Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
0
Indexable
Never
// Server
public class MyService : MyService.MyServiceBase
{
    public event EventHandler<MessageEventArgs> MessageReceived;

    public override async Task<Empty> SendMessage(Message request, ServerCallContext context)
    {
        // Trigger message received event
        MessageReceived?.Invoke(this, new MessageEventArgs(request));

        return new Empty();
    }
}

public class MessageEventArgs : EventArgs
{
    public Message Message { get; }

    public MessageEventArgs(Message message)
    {
        Message = message;
    }
}

// Client
public class MyClient
{
    private MyService.MyServiceClient _client;

    public event EventHandler<MessageEventArgs> MessageReceived;

    public async Task ConnectAsync(string host, int port)
    {
        var channel = new Channel($"{host}:{port}", ChannelCredentials.Insecure);
        _client = new MyService.MyServiceClient(channel);

        // Subscribe to server-side event
        var call = _client.SendMessage(new Message());
        await foreach (var response in call.ResponseStream.ReadAllAsync())
        {
            // Trigger message received event
            MessageReceived?.Invoke(this, new MessageEventArgs(response));
        }
    }

    public async Task SendMessageAsync(Message message)
    {
        await _client.SendMessageAsync(message);
    }
}

// Usage
var server = new MyService();
server.MessageReceived += (sender, e) =>
{
    var message = e.Message;
    // Handle server-side message received event
};

var client = new MyClient();
client.MessageReceived += (sender, e) =>
{
    var message = e.Message;
    // Handle client-side message received event
};

await server.StartAsync();

await client.ConnectAsync("localhost", 1234);
await client.SendMessageAsync(new Message());