/// <summary>
 /// 根据服务名获取服务地址
 /// </summary>
 /// <param name="serviceName"></param>
 /// <returns></returns>
 public RpcService GetRpcService(string serviceName)
 {
     using (var consul = BuildConsul())
     {
         //如果没有就直接随机Consul中取出的健康服务
         var discoveredServices = consul.Health.Service(serviceName, "", true).ConfigureAwait(false).GetAwaiter().GetResult().Response.Select(t => t.Service).ToList();//获取健康的服务
         var services           = new List <RpcService>();
         foreach (var discoveredService in discoveredServices)
         {
             var service = new RpcService()
             {
                 Name     = discoveredService.Service,
                 Host     = discoveredService.Address,
                 Port     = discoveredService.Port,
                 Protocol = ServiceProtocol.Http
             };
             if (discoveredService.Tags != null && discoveredService.Tags.Any(t => t.Equals(ServiceProtocol.Tcp.ToString())))
             {
                 service.Protocol = ServiceProtocol.Tcp;
             }
             services.Add(service);
         }
         return(_loadBalancer.GetService(services));
     };
 }
Example #2
0
        static void Main(string[] args)
        {
            Console.WriteLine("MachineName: {0}", Environment.MachineName);
            var slaveArgs = ParseArgs(args);

            if (slaveArgs == null)
            {
                return;
            }
            var pluginManager = new PluginManager(slaveArgs.DllFolder);
            var server        = new Server(new ChannelOption[]
            {
                // For Group, the received message size is very large, so here set 8000k
                new ChannelOption(ChannelOptions.MaxReceiveMessageLength, 8192000)
            })
            {
                Services = { RpcService.BindService(new RpcServiceImpl(pluginManager, slaveArgs.ModuleFullName)) },
                Ports    = { new ServerPort(slaveArgs.HostName, slaveArgs.Port, ServerCredentials.Insecure) }
            };

            server.Start();
            Console.WriteLine($"Server [{slaveArgs.HostName}:{slaveArgs.Port}] started");
            Console.WriteLine("Press any key to stop the server...");
            Console.ReadKey();

            server.ShutdownAsync().Wait();
            Task.Delay(Timeout.Infinite).Wait();
        }
Example #3
0
 /// <summary>
 /// 注销服务
 /// </summary>
 /// <param name="rpcService"></param>
 public void Deregister(RpcService rpcService)
 {
     using (var consul = BuildConsul())
     {
         consul.Agent.ServiceDeregister(GetServiceId(rpcService)).ConfigureAwait(false).GetAwaiter().GetResult();
     };
 }
Example #4
0
 protected ModuleHelper(LoggerService loggerService, ConfigService configService, SqliteDatabaseService sqliteDatabaseService, RpcService rpcService)
 {
     LoggerService         = loggerService;
     ConfigService         = configService;
     SqliteDatabaseService = sqliteDatabaseService;
     RpcService            = rpcService;
 }
Example #5
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine("MachineName: {0}", Environment.MachineName);
            var argsOption = new ArgsOption();
            var result     = Parser.Default.ParseArguments <ArgsOption>(args)
                             .WithParsed(options => argsOption = options)
                             .WithNotParsed(error => { });

            Grpc.Core.Server server = new Grpc.Core.Server(new ChannelOption[]
            {
                // For Group, the received message size is very large, so here set 8000k
                new ChannelOption(ChannelOptions.MaxReceiveMessageLength, 8192000)
            })
            {
                Services = { RpcService.BindService(new RpcServiceImpl()) },
                Ports    = { new ServerPort(argsOption.DnsName, argsOption.RpcPort, ServerCredentials.Insecure) }
            };
            server.Start();
            Console.WriteLine($"Server [{argsOption.DnsName}:{argsOption.RpcPort}] started");

            var pid = Process.GetCurrentProcess().Id;

            if (argsOption.PidFile != null)
            {
                Util.SaveContentToFile(argsOption.PidFile, Convert.ToString(pid), false);
            }
            await Task.Delay(Timeout.Infinite);
        }
        public void Build(PluginBuildContext ctx)
        {
            ctx.SceneCreated += scene =>
            {
                var rpcParams = scene.GetHostMetadata(PluginName);


                var processor = new RpcService(scene);
                scene.resolver.RegisterComponent(() => processor);
                scene.AddRoute(NextRouteName, p =>
                {
                    processor.Next(p);
                });
                scene.AddRoute(CancellationRouteName, p =>
                {
                    processor.Cancel(p);
                });
                scene.AddRoute(ErrorRouteName, p =>
                {
                    processor.Error(p);
                });
                scene.AddRoute(CompletedRouteName, p =>
                {
                    processor.Complete(p);
                });


            };
            ctx.SceneDisconnected += scene =>
                {
                    var processor = scene.resolver.GetComponent<RpcService>();
                    processor.Disconnected();
                };
        }
Example #7
0
 public AuthenticationController(IAuthenticationService auth, IUserSessions sessions, RpcService rpc, ILogger logger)
 {
     _auth         = auth;
     this.sessions = sessions;
     this.rpc      = rpc;
     this.logger   = logger;
 }
Example #8
0
        public void OnAppStarted()
        {
            RpcService.LoadServices();

            Program.Recorder.OnCall(SocketHandler.OnCall);

            Program.Recorder.OnDeviceConnected(SocketHandler.OnConnected);
            Program.Recorder.OnDeviceClosed(SocketHandler.OnClosed);

            Program.Recorder.OnDeviceError(SocketHandler.OnError);

            Program.Recorder.OnHangUp(SocketHandler.OnHangUp);
            Program.Recorder.OnHookOff(SocketHandler.OnHookOff);

            Program.Recorder.OnLineVoltage(SocketHandler.OnLineVoltage);

            Program.Recorder.OnRinging(SocketHandler.OnRinging);

            Program.Recorder.OnRingCancel(SocketHandler.OnRingCancel);

            Program.Recorder.OnLog(SocketHandler.OnLog);


            if (Program.Recorder.ConnectDevice())
            {
                Console.WriteLine("devices connecting...");
            }



            Process.Start(Path.Combine(Directory.GetCurrentDirectory(), "App", "UBoxCoreApp.exe"));
        }
Example #9
0
        private async ValueTask <int> callMethod(WebSocket socket, string data)
        {
            try
            {
                RPCRequest request = JsonConvert.DeserializeObject <RPCRequest>(data);

                switch (request.Method)
                {
                case "getStatus":
                    sendMessage(new RpcResponse {
                        Event = "OnDeviceStatus", Data = Program.Recorder.getCurrentChannel() != null ? "0" : "-1"
                    });
                    break;

                default:
                    var response = RpcService.Invoke(request);
                    sendMessage(response);
                    break;
                }
            }
            catch (Exception ex)
            {
                sendMessage(new RpcResponse {
                    Event = "OnError", Data = ex.Message
                });
            }



            return(0);
        }
Example #10
0
        public RpcService Get(string name, int version, string plataform)
        {
            RpcService       service = new RpcService();
            SQLiteConnection conn    = OpenNewConnection();

            try
            {
                lock (mutex)
                {
                    using (var cmdSelect = new SQLiteCommand(conn))
                    {
                        //TODO:
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("Some error in SQL Execution", e);
            }
            finally
            {
                CloseConnection(conn);
            }

            return(service);
        }
        /// <summary>
        /// 获取网络模块参数
        /// </summary>
        /// <param name="networkModuleCacheRequest"></param>
        /// <returns></returns>
        public BasicResponse <NetDeviceSettingInfo> GetNetworkModuletParameters(NetworkModuletParametersGetRequest networkModuleCacheRequest)
        {
            BasicResponse <NetDeviceSettingInfo> Result = new BasicResponse <NetDeviceSettingInfo>();

            QuerytNetworkDeviceParamRequest searchAssignNetDeviceRequest = new QuerytNetworkDeviceParamRequest();

            searchAssignNetDeviceRequest.Mac = networkModuleCacheRequest.Mac;
            //searchAssignNetDeviceRequest.WaitTime = networkModuleCacheRequest.WaitTime;
            //todo 调用RPC组件获取数据
            MasProtocol masProtocol = new MasProtocol(SystemType.Security, DirectionType.Down, ProtocolType.QuerytNetworkDeviceParamRequest);

            masProtocol.Protocol = searchAssignNetDeviceRequest;

            //调用RPC发送搜索网络模块命令,并接收回传的参数
            var result = RpcService.Send <QuerytNetworkDeviceParamResponse>(masProtocol, RequestType.DeviceUdpRequest);

            if (result == null)
            {
                Result.Code    = 1;
                Result.Message = "获取网络模块参数失败!";
                return(Result);
            }
            Result.Data = result.NetworkDeviceParam;

            return(Result);
        }
 public DiscordAppService(Program program, LoggerService loggerService, ConfigService configService, RpcService rpcService, SqliteDatabaseService sqliteDatabaseService)
 {
     Program               = program;
     LoggerService         = loggerService;
     ConfigService         = configService;
     RpcService            = rpcService;
     SqliteDatabaseService = sqliteDatabaseService;
 }
Example #13
0
        public List <RpcService> GetAll()
        {
            List <RpcService> services = new List <RpcService>();

            SQLiteConnection conn = OpenNewConnection();

            try
            {
                lock (mutex)
                {
                    using (var selectRpcService = new SQLiteCommand(conn))
                    {
                        selectRpcService.CommandText = @"SELECT * FROM rpcservice WHERE plataform = 'wp'";
                        selectRpcService.CommandType = CommandType.Text;

                        SQLiteDataReader rpcReader = selectRpcService.ExecuteReader();
                        while (rpcReader.Read())
                        {
                            RpcService service = new RpcService();
                            service.Id         = Convert.ToInt32(rpcReader["id"]);
                            service.Name       = Convert.ToString(rpcReader["name"]);
                            service.Port       = Convert.ToInt32(rpcReader["port"]);
                            service.VersionApp = Convert.ToString(rpcReader["version_app"]);

                            using (var selectDep = new SQLiteCommand(conn))
                            {
                                selectDep.CommandText = @"SELECT * FROM dependency_app WHERE id_service = " + service.Id + "";
                                selectDep.CommandType = CommandType.Text;

                                SQLiteDataReader depReader = selectDep.ExecuteReader();
                                while (depReader.Read())
                                {
                                    DependencePath dep = new DependencePath();
                                    dep.Id        = Convert.ToInt32(depReader["id"]);
                                    dep.IdService = Convert.ToInt32(depReader["id_service"]);
                                    dep.Path      = Convert.ToString(depReader["path"]);

                                    service.Dependencies.Add(dep);
                                }
                            }

                            services.Add(service);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("Some error in SQL Execution", e);
            }
            finally
            {
                CloseConnection(conn);
                services.Sort();
            }

            return(services);
        }
Example #14
0
 public void StartServiceRpc(RpcService service)
 {
     lock (instance)
     {
         RpcTcpServer server = new RpcTcpServer(ip, service);
         server.Start();
         RpcServices.Add(server);
     }
 }
Example #15
0
        static void Main(string[] args)
        {
            logger = new EmptyLogger();

            IRpcService service = new RpcService();

            service.StartService();

            Console.ReadKey();
            logger.Debug("q");
        }
 public GameFinderConfigController(
     IGameFinderConfigService gameFinderConfigService,
     RpcService rpc,
     ISerializer serializer,
     IServiceLocator locator
     )
 {
     _gameFinderConfigService = gameFinderConfigService;
     this.rpc        = rpc;
     this.serializer = serializer;
     this.locator    = locator;
 }
Example #17
0
 internal RtmpSession(IOPipeLine ioPipeline)
 {
     IOPipeline           = ioPipeline;
     ControlChunkStream   = new RtmpControlChunkStream(this);
     ControlMessageStream = new RtmpControlMessageStream(this);
     _messageStreams.Add(ControlMessageStream.MessageStreamId, ControlMessageStream);
     NetConnection = new NetConnection(this);
     ControlMessageStream.RegisterMessageHandler <SetChunkSizeMessage>(HandleSetChunkSize);
     ControlMessageStream.RegisterMessageHandler <WindowAcknowledgementSizeMessage>(HandleWindowAcknowledgementSize);
     ControlMessageStream.RegisterMessageHandler <SetPeerBandwidthMessage>(HandleSetPeerBandwidth);
     ControlMessageStream.RegisterMessageHandler <AcknowledgementMessage>(HandleAcknowledgement);
     _rpcService = ioPipeline.Options.ServerLifetime.Resolve <RpcService>();
 }
    public RpcCallSchemaModel(RpcService parentService, RpcCall call)
    {
        this.attributes = new(call.Attributes);
        this.fullName   = $"{parentService.Name}.{call.Name}";
        this.call       = call;

        new FlatSharpAttributeValidator(FlatBufferSchemaElementType.RpcCall, $"{parentService.Name}.{call.Name}")
        {
            StreamingTypeValidator = _ => AttributeValidationResult.Valid,
        }.Validate(this.attributes);

        this.ValidateHasSerializer(call.Request);
        this.ValidateHasSerializer(call.Response);
    }
        public TestClientFixture()
        {
            var sockets    = SocketProvider.CreateSockets().Result;
            var clientSock = sockets.Item1;
            var serverSock = sockets.Item2;

            Service = new RpcService <ITestService>(
                new NetworkRpcService(new TcpTransportLayer(serverSock)
                                      ));
            Caller = new RpcCaller <ITestService>(
                new NetworkRpcClient(new TcpTransportLayer(clientSock)
                                     ));
            Service.Export(new TestService());
            Client = Caller.CreateClient();
        }
Example #20
0
 public IRpcServer Create(string hostname, int port)
 {
     _hostname = hostname;
     _port     = port;
     _server   = new Grpc.Core.Server(new ChannelOption[]
     {
         // For Group, the received message size is very large, so here set 8000k
         new ChannelOption(ChannelOptions.MaxReceiveMessageLength, 8192000)
     })
     {
         Services = { RpcService.BindService(new RpcServiceImpl()) },
         Ports    = { new ServerPort(hostname, port, ServerCredentials.Insecure) }
     };
     return(this);
 }
Example #21
0
        public void RegisterDistinctServices()
        {
            var service1 = new RpcService("Service1");
            var service2 = new RpcService("Service2");
            var service3 = new RpcServiceStub();

            var mgr = new GlobalObjectManager();

            mgr.RegisterService(service1);
            mgr.RegisterService(service2);
            mgr.RegisterService(service3, "Service3");

            Assert.That(mgr.GetService("Service1"), Is.SameAs(service1));
            Assert.That(mgr.GetService("Service2"), Is.SameAs(service2));
            Assert.That(mgr.GetService("Service3"), Is.SameAs(service3));
        }
    public RpcServiceSchemaModel(Schema.Schema schema, RpcService service) : base(schema, service.Name, new FlatSharpAttributes(service.Attributes))
    {
        this.service       = service;
        this.interfaceName = $"I{this.Name}";
        this.calls         = new();

        if (service.Calls is not null)
        {
            foreach (var call in service.Calls)
            {
                this.calls.Add(new(service, call));
            }
        }

        this.AttributeValidator.RpcInterfaceValidator = _ => AttributeValidationResult.Valid;
    }
Example #23
0
        public void JsonRPCTest()
        {
            var transport = new Transport();

            // server side
            var service = new RpcService <JsonParser, JsonFormatter>();
            var r       = new TypeRegistry();
            var method  = r.RPCFunc((int a, int b) => a + b);

            service.Dispatcher.AddRequestMethod("Add", method);
            service.AddStream(transport.ServerSide);

            // client side
            var requestTransporter = new RPCTransporter <JsonParser, JsonFormatter>(
                transport.ClientSide);
            var factory = new RPCRequestManager <JsonParser, JsonFormatter>();

            factory.RequestObservable.Subscribe(requestTransporter);
            requestTransporter.ResponseObservable.Subscribe(factory);

            // call
            var f      = new RPCParamsFormatter <JsonFormatter>();
            int?result = null;

            factory.RequestAsync <int>("Add", f.Params(1, 2)).Subscribe(x =>
            {
                result = x;
            }
                                                                        , ex =>
            {
                throw ex;
            }
                                                                        );

            // wait result
            for (int i = 0; i < 100; ++i)
            {
                if (result.HasValue)
                {
                    break;
                }
                System.Threading.Thread.Sleep(100);
            }

            Assert.AreEqual(3, result.Value);
        }
        /// <summary>
        /// 向网关同步数据
        /// </summary>
        /// <param name="SendItemList"></param>
        /// <returns></returns>
        private bool SynchronousDataToGateway(List <AreaInfo> SendItemList)
        {
            foreach (AreaInfo areaInfo in SendItemList)
            {
                PartitionControlRequest partitionControlRequest = new PartitionControlRequest();

                if (string.IsNullOrEmpty(areaInfo.Areadescribe))
                {
                    partitionControlRequest.zoneId = "";//分区标识
                }
                else
                {
                    partitionControlRequest.zoneId = areaInfo.Areadescribe; //分区标识
                }
                partitionControlRequest.paTaskDN    = "";                   //分区广播接入号码[暂未使用]
                partitionControlRequest.zoneName    = areaInfo.Areaname;    //分区名称
                partitionControlRequest.almLinkUdn1 = "";                   //分区报警联动用户号码列表[暂未使用]
                partitionControlRequest.almLinkUdn2 = "";                   //分区报警联动用户号码列表[暂未使用]
                partitionControlRequest.almLinkUdn3 = "";                   //分区报警联动用户号码列表[暂未使用]

                partitionControlRequest.InfoState = areaInfo.InfoState;
                //调用RPC发送
                MasProtocol masProtocol = new MasProtocol(SystemType.Broadcast, DirectionType.Down, ProtocolType.PartitionControlRequest);
                masProtocol.Protocol = partitionControlRequest;
                PartitionControlResponse result = RpcService.Send <PartitionControlResponse>(masProtocol, RequestType.BusinessRequest);

                if (result == null && result.retCode != "0")
                {
                    Basic.Framework.Logging.LogHelper.Error("向网关同步广播分区信息失败!,分区名称:" + areaInfo.Areaname);
                    return(false);
                }
                else
                {
                    //将返回的分区标识更新到缓存及数据库  20180103
                    areaInfo.Areadescribe = result.zoneId;
                    //更新数据库
                    var _area = ObjectConverter.Copy <AreaInfo, AreaModel>(areaInfo);
                    _Repository.UpdateArea(_area);
                    //更新区域缓存  20171128
                    AreaCacheUpdateRequest AreaCacheUpdateRequest = new AreaCacheUpdateRequest();
                    AreaCacheUpdateRequest.AreaInfo = areaInfo;
                    _AreaCacheService.UpdateAreaCache(AreaCacheUpdateRequest);
                }
            }
            return(true);
        }
Example #25
0
        /// <summary>
        ///  Registers Rpc-related services with the Dependency Injection provider
        /// </summary>
        private void ConfigureRpcServices(IServiceCollection services)
        {
            // Register a Dispatching RPC Message Handler scoped for each function invocation
            // Configure this handler to send outgoing messages using IoT CloudToDeviceMethods
            services.AddScoped <DispatchingClientMessageHandler>((services) => {
                var serviceClient = services.GetService <ServiceClient>();
                var logger        = services.GetService <ILogger <FunctionsStartup> >();

                var handler = new DispatchingClientMessageHandler();

                handler.SendAsync = async(message, clientId) => {
                    logger.LogTrace($"Sending RPC message to {clientId}");
                    logger.LogTrace(message);

                    var method = new CloudToDeviceMethod(CLOUD_TO_DEVICE_METHOD_NAME);
                    method.SetPayloadJson(message);

                    await serviceClient.InvokeDeviceMethodAsync(clientId, method);

                    logger.LogTrace($"Successfully sent RPC message to {clientId}");
                };

                return(handler);
            });

            // Register a Function-scoped JsonRpc that uses the Message Handler
            services.AddScoped <JsonRpc>((services) =>
                                         new JsonRpc(services.GetService <DispatchingClientMessageHandler>())
            {
                CancelLocallyInvokedMethodsWhenConnectionIsClosed = false
            }
                                         );

            // Register a new SampleService instance that's an invocation target for JsonRpc
            services.AddScoped <IRpcService>((services) => {
                var jsonRpc = services.GetService <JsonRpc>();
                var handler = services.GetService <DispatchingClientMessageHandler>();
                var service = new RpcService();

                jsonRpc.AddLocalRpcTarget(service);
                jsonRpc.StartListening();

                return(service);
            });
        }
Example #26
0
        internal async Task RunServerAsync()
        {
            TcpListener listener = new TcpListener(IPAddress.Loopback, Program.lbPort);

            listener.Start();
            _barrier.SignalAndWait();
            var srvSock = await listener.AcceptTcpClientAsync();

            var service = new RpcService <IHelloService>(
                new NetworkRpcService(new TcpTransportLayer(srvSock)
                                      ));

            service.Export(new HelloService());
            Console.WriteLine($"{nameof(HelloService)} ready.");
            await Task.Delay(0);

            _barrier.SignalAndWait();
        }
Example #27
0
        public void Add(RpcService service)
        {
            SQLiteConnection conn = OpenNewConnection();

            try
            {
                lock (mutex)
                {
                    using (var cmdRpcService = new SQLiteCommand(conn))
                    {
                        using (var transaction = conn.BeginTransaction())
                        {
                            cmdRpcService.CommandText = @"INSERT INTO rpcservice (name,port,version_app,plataform) VALUES (@name, @port, @version_app, @plataform); SELECT last_insert_rowid();";
                            cmdRpcService.Parameters.AddWithValue("@name", service.Name);
                            cmdRpcService.Parameters.AddWithValue("@port", service.Port);
                            cmdRpcService.Parameters.AddWithValue("@version_app", service.VersionApp);
                            cmdRpcService.Parameters.AddWithValue("@plataform", "wp");

                            int id = Convert.ToInt32(cmdRpcService.ExecuteScalar().ToString());

                            using (var cmdDependence = new SQLiteCommand(conn))
                            {
                                foreach (DependencePath dep in service.Dependencies)
                                {
                                    cmdDependence.CommandText = @"INSERT INTO dependency_app (id_service,path) VALUES (@id_service, @path);";
                                    cmdDependence.Parameters.AddWithValue("@id_service", id);
                                    cmdDependence.Parameters.AddWithValue("@path", dep.Path);
                                    cmdDependence.ExecuteNonQuery();
                                }
                            }
                            transaction.Commit();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("Some error in SQL Execution", e);
            }
            finally
            {
                CloseConnection(conn);
            }
        }
        // POST: api/Form
        public FormModelResult Post(JObject form)
        {
            LogService.StartProcessLog(_log);
            FormModelResult formResult = new FormModelResult();

            try
            {
                if (ModelState.IsValid)
                {
                    LogService.SaveLog(_log, "Conexão com RabbitMQ aberta.");

                    LogService.SaveLog(_log, "Iniciando operação RPC.");

                    RpcService rpcService = new RpcService();

                    FormModel formModel = rpcService.ConvertToJsonToFormObj(form);

                    string body = rpcService.ConvertToJson(formModel).ToLower();

                    LogService.SaveLog(_log, "Chamada RPC.");

                    var response = rpcService.Call(body);

                    JObject jsonResult = JObject.Parse(response);

                    formResult = rpcService.ConvertFormModelToResult(formModel, jsonResult);

                    LogService.SaveLog(_log, "Conexão com RabbitMQ fechada.");
                }
                else
                {
                    LogService.SaveLog(_log, "Modelo de dados inválido - Por favor informe todos os dados!");
                }
            }
            catch (Exception ex)
            {
                LogService.SaveLog(_log, "Erro no processo. Erro: " + ex.Message);
            }

            LogService.FinishProcessLog(_log);

            return(formResult);
        }
Example #29
0
        public AppHost() : base()
        {
            RpcService.AllowedOrigins.Add("http://localhost:1987");

            //
            // A naplozas kikapcsolhato mivel az a teljesitmeny teszteket negativan befolyasolja.
            //

            if (Environment.GetCommandLineArgs().Any(arg => arg.ToLowerInvariant() == "-nolog"))
            {
                RpcService.LoggerFactory = null;
                Logger = null;
            }
            else
            {
                RpcService.LoggerFactory = ConsoleLogger.Create <AppHost>;
                Logger = RpcService.LoggerFactory();
            }
        }
 public void Register(RpcService rpcService)
 {
     using (var consul = BuildConsul())
     {
         var serviceRegistration = new AgentServiceRegistration()
         {
             ID      = GetServiceId(rpcService),
             Name    = rpcService.Name,
             Address = rpcService.Host,
             Port    = rpcService.Port,
             Check   = new AgentServiceCheck
             {
                 TCP      = $"{rpcService.Host}:{rpcService.Port}",
                 Interval = TimeSpan.FromSeconds(5),
                 Timeout  = TimeSpan.FromSeconds(2)
             }
         };
         var result = consul.Agent.ServiceRegister(serviceRegistration).ConfigureAwait(false).GetAwaiter().GetResult();
     };
 }
Example #31
0
        /// <summary>
        /// 向网关同步数据
        /// </summary>
        /// <param name="SendItemList"></param>
        /// <returns></returns>
        private bool SynchronousDataToGateway(List <Jc_DefInfo> SendItemList)
        {
            foreach (Jc_DefInfo deviceInfo in SendItemList)
            {
                TerminalControlRequest terminalControlRequest = new TerminalControlRequest();
                //查找分区标识
                AreaCacheGetByKeyRequest AreaCacheRequest = new AreaCacheGetByKeyRequest();
                AreaCacheRequest.Areaid = deviceInfo.Areaid;
                AreaInfo areaInfo = _areaCacheService.GetByKeyAreaCache(AreaCacheRequest).Data;
                if (areaInfo != null)
                {
                    terminalControlRequest.zoneId = areaInfo.Areadescribe;//分区标识
                }
                else
                {
                    Basic.Framework.Logging.LogHelper.Error("未找到广播设备对应的分区信息,设备标识:" + deviceInfo.Point);
                    return(false);
                }
                terminalControlRequest.termDN    = deviceInfo.Point; //终端号码
                terminalControlRequest.type      = deviceInfo.Bz6;   //终端类型
                terminalControlRequest.name      = deviceInfo.Wz;    //终端名称
                terminalControlRequest.record    = deviceInfo.Bz7;   //录音使能是否启用
                terminalControlRequest.auth      = deviceInfo.Bz8;   //注册鉴权是否启用
                terminalControlRequest.password  = deviceInfo.Bz9;   //注册鉴权密码
                terminalControlRequest.pa        = deviceInfo.Bz11;  //广播使能是否启用
                terminalControlRequest.cfuDN     = deviceInfo.Bz12;  //始终呼叫转移号码
                terminalControlRequest.cfxDN     = deviceInfo.Bz13;  //条件呼叫转移号码
                terminalControlRequest.InfoState = deviceInfo.InfoState;
                //调用RPC发送
                MasProtocol masProtocol = new MasProtocol(SystemType.Broadcast, DirectionType.Down, ProtocolType.TerminalControlRequest);
                masProtocol.Protocol = terminalControlRequest;
                TerminalControlResponse result = RpcService.Send <TerminalControlResponse>(masProtocol, RequestType.BusinessRequest);

                if (result == null && result.retCode != "0")
                {
                    Basic.Framework.Logging.LogHelper.Error("向网关同步广播设备信息失败!,设备标识:" + deviceInfo.Point);
                    return(false);
                }
            }
            return(true);
        }
 public string UsingNamespace(RpcService hService)
 {
     return string.Empty;
 }
Example #33
0
 public ClientSessionCodeGen(RpcService hService)
     : base(hService)
 {
 }
Example #34
0
        public ServerCodeGen(RpcService hService)
        {
            Name            = hService.Name;

            StringBuilder hSb = new StringBuilder();

            foreach (RpcMethodInfo hMethod in hService.Rpcs)
            {
                StringBuilder hParamList = new StringBuilder();

                hParamList.AppendFormat("T hContext, ");

                foreach (ParameterInfo hParam in hMethod.Method.GetParameters())
                {
                    hParamList.AppendFormat("{0} {1}, ", hParam.ParameterType.AsKeyword(), hParam.Name);
                }

                hParamList.Remove(hParamList.Length - 2, 2);

                hSb.AppendFormat("      public abstract {0} {1}({2});{3}", hMethod.Method.ReturnType.AsKeyword(), hMethod.Method.Name, hParamList, Environment.NewLine);
            }

            StringBuilder hCb = new StringBuilder();
            hService.Pair.Client.Rpcs.ToList().ForEach(hM => this.WriteServerCallbackMethod(hM, hCb));

            StringBuilder hPacketRegistration = new StringBuilder();

            foreach (RpcMethodInfo hMethod in hService.Rpcs)
            {
                hPacketRegistration.AppendFormat("                            Interpreter.RegisterAction<{0}>();{1}", hMethod.RequestAction.Name, Environment.NewLine);
            }

            foreach (RpcMethodInfo hMethod in hService.Pair.Client.Rpcs.Where(hR => hR.ResponseAction != null))
            {
                hPacketRegistration.AppendFormat("                            Interpreter.RegisterAction<{0}>();{1}", hMethod.ResponseAction.Name, Environment.NewLine);
            }

            foreach (RpcMethodInfo hMethod in hService.Pair.Client.Rpcs)
            {
                hPacketRegistration.AppendFormat("                            Interpreter.Register<{0}>();{1}", hMethod.Request.Name, Environment.NewLine);
            }

            hPacketRegistration.AppendLine("                            Interpreter.Warmup(5);");

            Code = string.Format(@"
                using System;
                using Netbase.Shared;
                using Netbase.Server;
                using {4};

                namespace {0}
                {{
                    public abstract class {1}<T> : ServerIOCP<T> where T: SessionIOCP, new()
                    {{
                        public {1}()
                        {{
            {3}
                        }}

                        {2}
                    }}
                }}
                ",
                hService.Namespace,
                Name,
                hSb.ToString(),
                hPacketRegistration,
                hService.Pair.Client.Namespace);
        }
Example #35
0
 public string UsingNamespace(RpcService hService)
 {
     return string.Format("using {0};", hService.Pair.Client.Namespace);
 }