Exemple #1
0
        public static void Run()
        {
            Server server = new Server();

            server.Ports.Add("127.0.0.1", 50001, ServerCredentials.Insecure);
            server.Services.Add(StatsService.BindService(new ServerImpl()));
            server.Start();

            Thread.Sleep(1000);

            var client = new StatsService.StatsServiceClient(new Channel("127.0.0.1", 50001, ChannelCredentials.Insecure));

            // Three different ways of computing the average of [1,2,3,4]. We're pretty sure it's 2.5 at this point.

            // Unary operations take one request and send one response.
            // Our operation includes the whole array of data.
            UnaryOperation(client).GetAwaiter().GetResult();

            // Client streaming operations let the client send many requests and the server sends one response.
            // The client streams the individual numbers it wants averaged, and the server sends the aggregated response at the end.
            ClientStreamingOperation(client).GetAwaiter().GetResult();

            // Duplex streaming operations let the client send a stream of requests and the server send a stream of responses.
            // We send the cumulative average after each request in this example.
            DuplexStreamingOperation(client).GetAwaiter().GetResult();

            // Server streaming operations are the opposite of client streaming. One client request results in a stream of server responses.
            // However, this is left as an exercise to the reader.

            Thread.Sleep(1000);

            server.ShutdownAsync().GetAwaiter().GetResult();
        }
Exemple #2
0
        private void GrpcInit()
        {
            if (channel_ == null)
            {
                Global.statePort = GetFreePort();

                channel_ = new Channel($"{Global.Loopback}:{Global.statePort}", ChannelCredentials.Insecure);
                channel_.ConnectAsync();
                client_ = new StatsService.StatsServiceClient(channel_);
            }
        }
Exemple #3
0
        static void Main(string[] args)
        {
            var builder = new HostBuilder();

            builder.UseConsoleLifetime()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .ConfigureAppConfiguration((host, config) =>
            {
                config.SetBasePath(Directory.GetCurrentDirectory());
                config.AddJsonFile("appsettings.json", true);
                config.AddJsonFile($"appsettings.{host.HostingEnvironment.EnvironmentName}.json", true);
                config.AddEnvironmentVariables(prefix: "APP_");
                config.AddCommandLine(args);
            })
            .ConfigureHostConfiguration(configHost =>
            {
                configHost.SetBasePath(Directory.GetCurrentDirectory());
                configHost.AddJsonFile("hostsettings.json", optional: true);
                configHost.AddEnvironmentVariables(prefix: "APPHOST");
                configHost.AddCommandLine(args);
            }).ConfigureLogging(loggerBuilder =>
            {
                loggerBuilder.AddConsole();
                loggerBuilder.AddDebug();
            }).ConfigureServices(services =>
            {
                services.AddHttpClient();
                services.AddLogging();
                services.AddSingleton <StatsService.StatsServiceClient>(provider =>
                {
                    IConfiguration config = provider.GetRequiredService <IConfiguration>();
                    string host           = config.GetConnectionString("V2Ray");
                    string[] hostInfo     = host.Split(':');
                    Channel channel       = new Channel(hostInfo[0], hostInfo.Length > 1 ? Convert.ToInt32(hostInfo[1]) : 80, ChannelCredentials.Insecure);
                    StatsService.StatsServiceClient client = new StatsService.StatsServiceClient(channel);
                    return(client);
                });
                services.AddSingleton <IV2RayCollectService, V2RayCollectService>();
                services.AddSingleton <IAsymmetric, RsaAsymmetricService>();
                services.AddSingleton <ISymmetric, AesCBCService>();
                services.AddHostedService <TimeBasedService>();
            });
            builder.Build().Run();
        }
Exemple #4
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            // 初始化日志目录
            if (!Directory.Exists("logging"))
            {
                Directory.CreateDirectory("logging");
            }

            // 初始化配置
            Config.InitFromFile();

            // 初始化代理
            InitProxies();
            if (ProxyComboBox.Items.Count > 0)
            {
                ProxyComboBox.SelectedIndex = 0;
            }

            // 初始化模式
            ModeComboBox.SelectedIndex = 0;

            // 初始化适配器
            Task.Run(() =>
            {
                using (var client = new UdpClient("114.114.114.114", 53))
                {
                    var address = ((IPEndPoint)client.Client.LocalEndPoint).Address;
                    Global.Config.adapterAddress = address.ToString();

                    var addressGeted = false;

                    var adapters = NetworkInterface.GetAllNetworkInterfaces();
                    foreach (var adapter in adapters)
                    {
                        var properties = adapter.GetIPProperties();

                        foreach (var information in properties.UnicastAddresses)
                        {
                            if (information.Address.AddressFamily == AddressFamily.InterNetwork && Equals(information.Address, address))
                            {
                                addressGeted = true;
                            }
                        }

                        foreach (var information in properties.GatewayAddresses)
                        {
                            if (addressGeted)
                            {
                                Global.Config.adapterGateway = information.Address.ToString();
                                break;
                            }
                        }

                        if (addressGeted)
                        {
                            break;
                        }
                    }
                }
            });

            // 后台工作
            Task.Run(() =>
            {
                while (true)
                {
                    try
                    {
                        Invoke(new MethodInvoker(() =>
                        {
                            // 更新标题栏时间
                            Text = string.Format("x2tap - {0}", DateTime.Now.ToString());

                            // 更新状态信息
                            StatusLabel.Text = string.Format("状态:{0}", Status);
                        }));

                        // 更新流量信息
                        if (Started)
                        {
                            var channel   = new Channel("127.0.0.1:2811", ChannelCredentials.Insecure);
                            var asyncTask = channel.ConnectAsync();

                            asyncTask.Wait(100);
                            if (asyncTask.IsCompleted)
                            {
                                // 创建客户端实例
                                var client = new StatsService.StatsServiceClient(channel);

                                // 获取并重置 上行/下行 统计信息
                                var uplink = client.GetStats(new GetStatsRequest {
                                    Name = "inbound>>>defaultInbound>>>traffic>>>uplink", Reset = true
                                });
                                var downlink = client.GetStats(new GetStatsRequest {
                                    Name = "inbound>>>defaultInbound>>>traffic>>>downlink", Reset = true
                                });

                                // 加入总流量
                                Bandwidth += uplink.Stat.Value;
                                Bandwidth += downlink.Stat.Value;

                                // 更新流量信息
                                Invoke(new MethodInvoker(() =>
                                {
                                    UsedBandwidthLabel.Text = $"已使用:{Util.ComputeBandwidth(Bandwidth)}";
                                    UplinkSpeedLabel.Text   = $"↑:{Util.ComputeBandwidth(uplink.Stat.Value)}/s";
                                    DownlinkSpeedLabel.Text = $"↓:{Util.ComputeBandwidth(downlink.Stat.Value)}/s";
                                }));
                            }
                        }
                        else
                        {
                            Bandwidth = 0;
                            UsedBandwidthLabel.Text = "已使用:0 KB";
                            UplinkSpeedLabel.Text   = "↑:0 KB/s";
                            DownlinkSpeedLabel.Text = "↓:0 KB/s";
                        }

                        // 休眠 1000 毫秒
                        Thread.Sleep(1000);
                    }
                    catch (Exception)
                    {
                        // 跳过
                    }
                }
            });
        }
Exemple #5
0
 private static async Task ClientStreamingOperation(StatsService.StatsServiceClient client)
 {
     AsyncClientStreamingCall <SingleNumber, AverageResponse> call = client.AverageStreaming(default);
Exemple #6
0
        private static async Task UnaryOperation(StatsService.StatsServiceClient client)
        {
            AverageResponse response = await client.SingleOperation(new BulkNumbers { Items = new[] { 1d, 2d, 3d, 4d } });

            Console.WriteLine("[Unary] Average is: " + response.Average);
        }
 public V2RayCollectService(StatsService.StatsServiceClient client, ILogger <V2RayCollectService> logger)
 {
     this.client = client;
     this.logger = logger;
 }
Exemple #8
0
 private void grpcInit()
 {
     channel_ = new Channel($"127.0.0.1:{Global.InboundAPIPort}", ChannelCredentials.Insecure);
     channel_.ConnectAsync();
     client_ = new StatsService.StatsServiceClient(channel_);
 }