KafkaSR/RPG.Services.Core/Network/ServiceBox.cs
2024-01-30 02:49:21 +03:00

52 lines
1.6 KiB
C#

using System.Collections.Immutable;
using Microsoft.Extensions.Options;
using NetMQ;
using NetMQ.Sockets;
using RPG.Network.Proto;
using RPG.Services.Core.Options;
namespace RPG.Services.Core.Network;
public class ServiceBox
{
private readonly IOptions<ServiceNodeOptions> _nodeOptions;
private readonly IOptions<RPGServiceOptions> _serviceOptions;
private ImmutableDictionary<RPGServiceType, NetMQSocket>? _sockets;
public ServiceBox(IOptions<ServiceNodeOptions> nodeOptions, IOptions<RPGServiceOptions> serviceOptions)
{
_nodeOptions = nodeOptions;
_serviceOptions = serviceOptions;
}
public RPGServiceType CurrentType => _serviceOptions.Value.ServiceType;
public void Construct()
{
var builder = ImmutableDictionary.CreateBuilder<RPGServiceType, NetMQSocket>();
foreach (ServiceNodeOptions.Entry entry in _nodeOptions.Value)
{
if (entry.Type == CurrentType) continue;
NetMQSocket socket = new PushSocket($">tcp://{entry.Host}:{entry.Port}");
socket.Options.SendHighWatermark = 10000;
builder.Add(entry.Type, socket);
}
_sockets = builder.ToImmutable();
}
public void SendToService(RPGServiceType serviceType, byte[] data)
{
if (_sockets == null) throw new InvalidOperationException("SendToService called when socket map not constructed!");
if (_sockets.TryGetValue(serviceType, out NetMQSocket? socket))
{
lock (socket)
{
socket.SendFrame(data);
}
}
}
}