using System; using System.Threading.Tasks; using System.Net; using System.Net.Sockets; using Grpc.Core; using Aurora.Services.Server.Controllers; using Aurora.Proto.PartyV2; namespace Aurora.Services.Server { public class ServerService : BaseService { private int _port = 8080; private string _hostname; private Grpc.Core.Server _server; //Implementation class declarations private RemotePartyController _remotePartyController; /// /// Constructor. Registers GRPC service implementations. /// public ServerService() { string host = GetLocalIPAddress(); if (string.IsNullOrWhiteSpace(host)) { throw new Exception("This device must have a valid IP address"); } _hostname = host; _server = new Grpc.Core.Server { Ports = { new ServerPort(_hostname, _port, ServerCredentials.Insecure) } }; } public int Port { get { return _port; } } public string Hostname { get { return _hostname; } } public bool Initialized { get { return (_remotePartyController != null && _server != null); } } /// /// Start Server /// public void Start(string partyName, string description) { try { Console.WriteLine(string.Format("Starting gRPC server at hostname: {0}, port: {1}", _hostname, _port)); if (!Initialized) { //Construct implementations _remotePartyController = new RemotePartyController(partyName, description); // Register grpc RemoteService with singleton server service RegisterService(RemotePartyService.BindService(_remotePartyController)); } _server.Start(); } catch (Exception ex) { Console.WriteLine(string.Format("Error starting gRPC server: {0}", ex.Message)); } } /// /// Shutdown server async. /// /// Task public async Task Stop() { await _server.ShutdownAsync(); } public async Task Reset() { await Stop(); _server = new Grpc.Core.Server { Ports = { new ServerPort("localhost", _port, ServerCredentials.Insecure) } }; } private void RegisterService(ServerServiceDefinition definition) { _server.Services.Add(definition); } public static string GetLocalIPAddress() { string returnIp = ""; var host = Dns.GetHostEntry(Dns.GetHostName()); foreach (var ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { returnIp = ip.ToString(); } } return returnIp; } } }