2024-01-18 22:13:40 +00:00
|
|
|
|
using NetMQ;
|
|
|
|
|
using NetMQ.Sockets;
|
|
|
|
|
using RPG.Services.Core.Network.Command;
|
|
|
|
|
using RPG.Services.Core.Options;
|
|
|
|
|
|
|
|
|
|
namespace RPG.Services.Core.Network;
|
|
|
|
|
internal class ServiceEndPoint
|
|
|
|
|
{
|
|
|
|
|
private readonly NetMQSocket _socket;
|
|
|
|
|
|
|
|
|
|
private CancellationTokenSource? _receiveCancellation;
|
|
|
|
|
|
|
|
|
|
public delegate Task CommandEventHandler(ServiceCommand command);
|
|
|
|
|
public event CommandEventHandler? OnCommand;
|
|
|
|
|
|
|
|
|
|
public ServiceEndPoint(ServiceNodeOptions.Entry optionsEntry)
|
|
|
|
|
{
|
|
|
|
|
_socket = new PullSocket($"@tcp://{optionsEntry.Host}:{optionsEntry.Port}");
|
|
|
|
|
_socket.Options.ReceiveHighWatermark = 10000;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Start()
|
|
|
|
|
{
|
|
|
|
|
_receiveCancellation = new();
|
2024-01-19 22:39:12 +00:00
|
|
|
|
_ = Task.Run(() => Receive(_receiveCancellation.Token));
|
2024-01-18 22:13:40 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private async Task Receive(CancellationToken cancellationToken)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
while (!cancellationToken.IsCancellationRequested)
|
|
|
|
|
{
|
|
|
|
|
NetMQMessage netMessage = _socket.ReceiveMultipartMessage();
|
|
|
|
|
while (!netMessage.IsEmpty)
|
|
|
|
|
{
|
|
|
|
|
byte[] buffer = netMessage.Pop().Buffer;
|
|
|
|
|
if (OnCommand != null)
|
|
|
|
|
await OnCommand(ServiceCommandEncoder.DecodeCommand(buffer));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-01-19 22:39:12 +00:00
|
|
|
|
catch
|
2024-01-18 22:13:40 +00:00
|
|
|
|
{
|
2024-01-19 22:39:12 +00:00
|
|
|
|
if (!_socket.IsDisposed) _socket.Close();
|
2024-01-18 22:13:40 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task StopAsync()
|
|
|
|
|
{
|
2024-01-19 22:39:12 +00:00
|
|
|
|
if (_receiveCancellation != null)
|
2024-01-18 22:13:40 +00:00
|
|
|
|
{
|
|
|
|
|
await _receiveCancellation.CancelAsync();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|