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 _nodeOptions; private readonly IOptions _serviceOptions; private ImmutableDictionary? _sockets; public ServiceBox(IOptions nodeOptions, IOptions serviceOptions) { _nodeOptions = nodeOptions; _serviceOptions = serviceOptions; } public RPGServiceType CurrentType => _serviceOptions.Value.ServiceType; public void Construct() { var builder = ImmutableDictionary.CreateBuilder(); 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); } } } }