Imported Upstream version 1.33.2
[platform/upstream/grpc.git] / examples / csharp / HelloworldXamarin / HelloworldXamarin / MainPage.xaml.cs
1 #region Copyright notice and license
2 // Copyright 2020 The gRPC Authors
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 #endregion
16
17 using System;
18 using System.Collections.Generic;
19 using System.ComponentModel;
20 using System.Linq;
21 using System.Text;
22 using System.Threading.Tasks;
23 using Xamarin.Forms;
24 using Grpc.Core;
25 using Helloworld;
26
27 namespace HelloworldXamarin
28 {
29     public partial class MainPage : ContentPage
30     {
31         const int Port = 30051;
32         int count = 1;
33
34         public MainPage()
35         {
36             InitializeComponent();
37         }
38
39         private void Button_Clicked(object sender, EventArgs e)
40         {
41             SayHello(sender as Button);
42         }
43
44         private void SayHello(Button button)
45         {
46             Server server = new Server
47             {
48                 Services = { Greeter.BindService(new GreeterImpl()) },
49                 Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) }
50             };
51             server.Start();
52
53             // use loopback on host machine: https://developer.android.com/studio/run/emulator-networking
54             // 10.0.2.2:30051
55             Channel channel = new Channel("localhost:30051", ChannelCredentials.Insecure);
56
57             var client = new Greeter.GreeterClient(channel);
58             string user = "Xamarin " + count;
59
60             var reply = client.SayHello(new HelloRequest { Name = user });
61
62             button.Text = "Greeting: " + reply.Message;
63
64             channel.ShutdownAsync().Wait();
65             server.ShutdownAsync().Wait();
66
67             count++;
68         }
69
70         class GreeterImpl : Greeter.GreeterBase
71         {
72             // Server side handler of the SayHello RPC
73             public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
74             {
75                 return Task.FromResult(new HelloReply { Message = "Hello " + request.Name });
76             }
77         }
78     }
79 }