Пример #1
0
        private static async Task SaveAllAsync(EmployeeService.EmployeeServiceClient client)
        {
            var employees = new List <Employee>
            {
                new Employee {
                    BadgeNumber = 2, FirstName = "Sunny", LastName = "Hook", Id = 22, VacationAccurateRate = 2.1F, VacationAccured = 1.2F
                },
                new Employee {
                    BadgeNumber = 3, FirstName = "Cheese", LastName = "Burger", Id = 33, VacationAccurateRate = 2.1F, VacationAccured = 1.2F
                }
            };

            using (var call = client.SaveAll())
            {
                var requestStream  = call.RequestStream;
                var responseStream = call.ResponseStream;
                var responseTask   = Task.Run(async() =>
                {
                    while (await responseStream.MoveNext())
                    {
                        Console.WriteLine("Saved: " + responseStream.Current.Employee);
                    }
                });
                foreach (var e in employees)
                {
                    await requestStream.WriteAsync(new EmployeeRequest { Employee = e });
                }
                await requestStream.CompleteAsync();

                await responseTask; //order is important.
            }
        }
Пример #2
0
        public static async Task SaveAllAsync(EmployeeService.EmployeeServiceClient client)
        {
            var employes = new List <Employee>
            {
                new Employee
                {
                    No        = 111,
                    FirstName = "monica",
                    LastName  = "Geller",
                    //Salary = 7916.1f
                    MonthSalary = new MonthSalary
                    {
                        Basic = 5000f,
                        Bonus = 125.5f
                    },
                    Status       = EmployeeStatus.Resigned,
                    LastModified = Timestamp.FromDateTime(DateTime.UtcNow)
                },
                new Employee
                {
                    No        = 112,
                    FirstName = "Joey",
                    LastName  = "Tribbiani",
                    //Salary = 500
                    MonthSalary = new MonthSalary
                    {
                        Basic = 5000f,
                        Bonus = 125.5f
                    },
                    Status       = EmployeeStatus.Resigned,
                    LastModified = Timestamp.FromDateTime(DateTime.UtcNow)
                }
            };

            using var call = client.SaveAll();
            var resquestStream = call.RequestStream;
            var responseStream = call.ResponseStream;


            var responseTask = Task.Run(async() =>
            {
                while (await responseStream.MoveNext())
                {
                    Console.WriteLine($"Saved: {responseStream.Current.Employee}");
                }
            });

            foreach (var employee in employes)
            {
                await resquestStream.WriteAsync(new EmployeeRequest
                {
                    E = employee
                });
            }

            await resquestStream.CompleteAsync();

            await responseTask;
        }
Пример #3
0
        public static async Task SaveAllAsync(EmployeeService.EmployeeServiceClient client)
        {
            var employees = new List <Employee>
            {
                new Employee
                {
                    No          = 111,
                    FirstName   = "CC",
                    LastName    = "DD",
                    MonthSalary = new MonthSalary
                    {
                        Basic = 5000f,
                        Bouns = 125.5f
                    },
                    Status       = EmployeeStatus.Normal,
                    LastModified = Timestamp.FromDateTime(DateTime.UtcNow)
                },
                new Employee
                {
                    No          = 222,
                    FirstName   = "CAC",
                    LastName    = "DDT",
                    MonthSalary = new MonthSalary
                    {
                        Basic = 5000f,
                        Bouns = 125.5f
                    },
                    Status       = EmployeeStatus.Normal,
                    LastModified = Timestamp.FromDateTime(DateTime.UtcNow)
                }
            };

            using var call = client.SaveAll();
            var requestStream  = call.RequestStream;
            var responseStream = call.ResponseStream;

            var responseTask = Task.Run(async() =>
            {
                while (await responseStream.MoveNext())
                {
                    Console.WriteLine($"Saved: {responseStream.Current.Employee}");
                }
            });

            foreach (var employee in employees)
            {
                await requestStream.WriteAsync(new EmployeeRequest
                {
                    Employee = employee
                });;
            }

            await requestStream.CompleteAsync();

            await responseTask;
        }
Пример #4
0
        private static async Task SaveAllAsync(EmployeeService.EmployeeServiceClient client)
        {
            var employees = new List <Employee>
            {
                new Employee
                {
                    Id        = 111,
                    FirstName = "Monica",
                    LastName  = "Geller",
                    Salary    = 7890.1f,
                },
                new Employee
                {
                    No        = 222,
                    FirstName = "Joey",
                    LastName  = "Tribbiani",
                    Salary    = 500
                }
            };


            var call = client.SaveAll();

            //因为两端都是用流的方式传输,所以需要获取两个流示例
            var requestStream  = call.RequestStream;
            var responseStream = call.ResponseStream;

            //创建一个响应流Task,用于接收服务器端返回的消息
            var responseTask = Task.Run(async() =>
            {
                while (await responseStream.MoveNext())
                {
                    Console.WriteLine($"Saved:{responseStream.Current.Employee}");
                }
            });

            //像之前一样,向请求流中写入数据
            foreach (var employee in employees)
            {
                await requestStream.WriteAsync(new EmployeeRequest
                {
                    Employee = employee
                });
            }

            //顺序不可调换,否则会一直收不到服务器端返回的消息
            await requestStream.CompleteAsync();

            await responseTask;
        }
Пример #5
0
        public static async Task SaveAllAsync(EmployeeService.EmployeeServiceClient client)
        {
            var employees = new List <Employee>
            {
                new Employee
                {
                    No        = 111,
                    FirstName = "EEEEE",
                    LastName  = "Geller",
                    Salary    = 7800.9f
                },
                new Employee
                {
                    No        = 222,
                    FirstName = "John",
                    LastName  = "Tril",
                    Salary    = 533f
                }
            };

            using var call = client.SaveAll();
            var requestStream  = call.RequestStream;
            var responseStream = call.ResponseStream;

            var responseTask = Task.Run(async() =>
            {
                while (await responseStream.MoveNext())
                {
                    Console.WriteLine($"Saved:{ responseStream.Current.Info }");
                }
            });

            // 发送请求的逻辑
            foreach (var employee in employees)
            {
                await requestStream.WriteAsync(new EmployeeRequest
                {
                    Employee = employee
                });
            }

            await requestStream.CompleteAsync();

            await responseTask;
        }
Пример #6
0
        //duplex stream
        static async Task SaveAll(EmployeeService.EmployeeServiceClient client)
        {
            var employees = new List <Employee>
            {
                new Employee
                {
                    Id                  = 123,
                    BadgeNumber         = 1,
                    FirstName           = "Ermir",
                    LastName            = "Beqiraj",
                    VacationAccrualRate = 1.7f,
                    VacationAccrued     = 10
                }
            };

            using (var call = client.SaveAll())
            {
                var requestStream  = call.RequestStream;
                var responseStream = call.ResponseStream;

                // !important note: as soon as first request is made, we don't know how the server will response,
                // it may respond directly after first request, or it might collect responses
                // and respond after all requests have been finished,
                // so: we should handle responses async from requests
                var responseTask = Task.Run(async() =>
                {
                    while (await responseStream.MoveNext())
                    {
                        Console.WriteLine($"Saved : {responseStream.Current.Employee}");
                    }
                });


                foreach (var item in employees)
                {
                    await requestStream.WriteAsync(new EmployeeRequest { Employee = item });
                }
                // let server know we are done sending requests
                await requestStream.CompleteAsync();

                // wait after letting server know we finished requests
                await responseTask;
            }
        }
Пример #7
0
        public static async Task SaveAllAsync(EmployeeService.EmployeeServiceClient client)
        {
            var employees = new List <Employee>
            {
                new Employee
                {
                    No        = 666,
                    FirstName = "lll",
                    LastName  = "H"
                },
                new Employee
                {
                    No        = 777,
                    FirstName = "qqq",
                    LastName  = "G"
                }
            };

            using var call = client.SaveAll();
            var requestStream  = call.RequestStream;
            var responseStream = call.ResponseStream;

            var responseTask = Task.Run(async() =>
            {
                while (await responseStream.MoveNext())
                {
                    Log.Debug($"saved: {responseStream.Current.Employee}");
                    Console.WriteLine($"saved: {responseStream.Current.Employee}");
                }
            });

            foreach (var employee in employees)
            {
                await requestStream.WriteAsync(new EmployeeRequest
                {
                    Employee = employee
                });
            }

            await requestStream.CompleteAsync();

            await responseTask;
        }
Пример #8
0
        static async Task SaveAll(EmployeeService.EmployeeServiceClient client)
        {
            using var call = client.SaveAll();
            var requestStream  = call.RequestStream;
            var responseStream = call.ResponseStream;

            var employees = new List <Employee> {
                new Employee
                {
                    Id        = 5,
                    No        = 1002,
                    FirstName = "ye",
                    LastName  = "feng",
                    Salary    = 2203
                },
                new Employee
                {
                    Id        = 6,
                    No        = 1004,
                    FirstName = "liu",
                    LastName  = "jie",
                    Salary    = 3443
                },
            };

            var responseTask = Task.Run(async() => {
                while (await responseStream.MoveNext())
                {
                    Console.WriteLine($"Save Employee {responseStream.Current.Employee}");
                }
            });

            foreach (var employee in employees)
            {
                await requestStream.WriteAsync(new EmployeeRequest { Employee = employee });
            }

            await requestStream.CompleteAsync();

            await responseTask;
        }
Пример #9
0
        public async Task <List <Models.Employee> > SaveAllAsync(List <Models.Employee> employees)
        {
            var result = new List <Models.Employee>();
            var _mutex = new Mutex();

            using (var call = _employeeServiceClient.SaveAll())
            {
                var responseReaderTask = Task.Run(async() =>
                {
                    while (await call.ResponseStream.MoveNext())
                    {
                        _mutex.WaitOne();

                        result.Add(_employeeConverter.ToModel(call.ResponseStream.Current.Employee));

                        _mutex.ReleaseMutex();
                    }
                });

                foreach (var emp in employees)
                {
                    var request = new ProtocolBuffers.EmployeeRequest
                    {
                        Employee = _employeeConverter.ToMessage(emp)
                    };
                    await call.RequestStream.WriteAsync(request);
                }
                ;

                await call.RequestStream.CompleteAsync();

                await responseReaderTask;
            }


            return(result);
        }
Пример #10
0
        /// <summary>
        /// server streaming and client streaming
        /// </summary>
        /// <param name="client"></param>
        /// <returns></returns>
        public static async Task SaveAllAsync(EmployeeService.EmployeeServiceClient client)
        {
            //using 是c#8 新的语法糖,当执行完当前方法后,cal对象会被释放掉
            var md = new Metadata()
            {
                { "client", "10.2.39.38" },
                { "message", "I am client" },
            };

            using var cal = client.SaveAll(md);
            var stream       = cal.RequestStream;
            var serverStream = cal.ResponseStream;
            var responseTask = Task.Run(async() =>
            {
                var serverMD = await cal.ResponseHeadersAsync;
                foreach (var pair in serverMD)
                {
                    Console.WriteLine($"Server key:{pair.Key},value:{pair.Value}");
                }
                while (await serverStream.MoveNext())
                {
                    var serverData = serverStream.Current.Employee;
                    Console.WriteLine($"Client received data:{serverData}");
                }
            });

            foreach (var employeeRequest in employeeRequests)
            {
                await stream.WriteAsync(employeeRequest);
            }
            //告诉server端数据已全部传输完毕.
            await stream.CompleteAsync();

            //先后顺序有要求,要client先发completed,之后才能调用启动接收server response的task,不然server端不知道client
            //何时终止,不会继续往下面执行
            await responseTask;
        }
Пример #11
0
        public static async Task SaveAllAsync(EmployeeService.EmployeeServiceClient client)
        {
            var employees = new List <Employee>
            {
                new Employee
                {
                    No        = 111,
                    FirstName = "Monica",
                    LastName  = "Geller",
                    //Salary = 7890.1f
                    MonthSalary = new MonthSalary
                    {
                        Basic = 600f,
                        Bonus = 45.5f
                    },
                    Status     = EmloyeeStatus.Resigned,
                    LastModify = Timestamp.FromDateTime(DateTime.UtcNow)
                },
                new Employee
                {
                    No        = 222,
                    FirstName = "Joey",
                    LastName  = "Tribbiani",
                    //Salary = 500
                    MonthSalary = new MonthSalary
                    {
                        Basic = 560f,
                        Bonus = 155.5f
                    },
                    Status     = EmloyeeStatus.Retired,
                    LastModify = Timestamp.FromDateTime(DateTime.UtcNow)
                }
            };

            try
            {
                if (!NeedToken() || await GetTokenAsync(client))
                {
                    var headers = new Metadata
                    {
                        { "Authorization", $"Bearer {_token}" }
                    };

                    using var call = client.SaveAll(headers);
                    var requestStream  = call.RequestStream;
                    var responseStream = call.ResponseStream;

                    var responseTask = Task.Run(async() =>
                    {
                        while (await responseStream.MoveNext())
                        {
                            Console.WriteLine($"Saved: {responseStream.Current.Employee}");
                        }
                    });

                    foreach (var employee in employees)
                    {
                        await requestStream.WriteAsync(new EmployeeRequest
                        {
                            Employee = employee
                        });
                    }

                    await requestStream.CompleteAsync();

                    await responseTask;
                }
            }
            catch (RpcException e)
            {
                Log.Logger.Error($"{JsonConvert.SerializeObject(e.Trailers)}");
                Log.Logger.Error(e.Message);
            }
        }
Пример #12
0
        public async Task SaveAll()
        {
            var employees = new List <Employee> {
                new Employee {
                    No           = 222,
                    FirstName    = "张三",
                    Id           = 5,
                    Salary       = 143.23f,
                    Status       = EmployeeStatus.OnVacation,
                    LastModified = Timestamp.FromDateTime(DateTime.UtcNow),
                },
                new Employee {
                    No        = 444,
                    FirstName = "李四",
                    Id        = 6,
                    Salary    = 33.33f
                }
            };

            //传入元数据
            var md = new Metadata
            {
                { "username", "jack" },
                { "role", "admin" }
            };

            using var channel = GrpcChannel.ForAddress("http://localhost:6001");
            var client = new EmployeeService.EmployeeServiceClient(channel);

            using var call = client.SaveAll();
            var requestStream  = call.RequestStream;
            var responseStream = call.ResponseStream;

            //var responseTask = Task.Run(async () =>
            //{
            //    while (await responseStream.MoveNext())
            //    {
            //        Console.WriteLine($"接收:{responseStream.Current.Employee}");
            //    }
            //});

            var responseTask = await Task.Factory.StartNew(async() =>
            {
                while (await responseStream.MoveNext())
                {
                    Console.WriteLine($"接收:{responseStream.Current.Employee}");
                }
            });

            foreach (var employee in employees)
            {
                await requestStream.WriteAsync(new EmployeeRequest
                {
                    Employee = employee
                });
            }
            await requestStream.CompleteAsync(); //通知服务端请求结束

            //await responseTask必须位于requestStream.CompleteAsync()之后
            await responseTask;
        }
Пример #13
0
        static async Task Main(string[] args)
        {
            var metaDatas = new Metadata
            {
                { "username", "Leon" },
                { "role", "administrator" },
            };

            using var channel = GrpcChannel.ForAddress("https://localhost:5001");
            var client = new EmployeeService.EmployeeServiceClient(channel);

            var response = await client.GetByNoAsync(new GetByNoRequest()
            {
                No = 102
            }, metaDatas);

            Console.WriteLine(response.Employee.FirstName);

            using var getAllCall = client.GetAll(new GetAllRequest());
            var responseStream = getAllCall.ResponseStream;

            while (await responseStream.MoveNext())
            {
                Console.WriteLine(responseStream.Current.Employee.FirstName);
            }

            FileStream fileStream = File.OpenRead("Dream_x280.jpg");

            using var uploadPhotoCall = client.UploadPhoto();
            while (fileStream.Position < fileStream.Length)
            {
                var buffer = new byte[1024];
                int length = await fileStream.ReadAsync(buffer, 0, buffer.Length);

                if (length < buffer.Length)
                {
                    Array.Resize(ref buffer, length);
                }

                await uploadPhotoCall.RequestStream.WriteAsync(
                    new UploadPhotoRequest()
                {
                    Data = ByteString.CopyFrom(buffer)
                });
            }
            await uploadPhotoCall.RequestStream.CompleteAsync();


            using var saveAllCall = client.SaveAll();
            for (int index = 0; index < 5; index++)
            {
                await saveAllCall.RequestStream.WriteAsync(new EmployeeRequest()
                {
                    Employee = new Employee()
                    {
                        Id        = 10 + index,
                        FirstName = "Employee",
                        LastName  = index.ToString(),
                        No        = 110 + index,
                        Salary    = 10000 + index * 1000,
                    }
                });
            }
            await saveAllCall.RequestStream.CompleteAsync();

            while (await saveAllCall.ResponseStream.MoveNext())
            {
                Console.WriteLine(saveAllCall.ResponseStream.Current.Employee.Id);
            }

            Console.ReadLine();
        }