1 #region Copyright notice and license 2 3 // Copyright 2018 The gRPC Authors 4 // 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, software 12 // distributed under the License is distributed on an "AS IS" BASIS, 13 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 // See the License for the specific language governing permissions and 15 // limitations under the License. 16 17 #endregion 18 19 using Android.App; 20 using Android.Widget; 21 using Android.OS; 22 using System.Threading.Tasks; 23 using Grpc.Core; 24 using Helloworld; 25 26 namespace HelloworldXamarin.Droid 27 { 28 [Activity(Label = "HelloworldXamarin", MainLauncher = true, Icon = "@mipmap/icon")] 29 public class MainActivity : Activity 30 { 31 const int Port = 50051; 32 int count = 1; 33 OnCreate(Bundle savedInstanceState)34 protected override void OnCreate(Bundle savedInstanceState) 35 { 36 base.OnCreate(savedInstanceState); 37 38 // Set our view from the "main" layout resource 39 SetContentView(Resource.Layout.Main); 40 41 // Get our button from the layout resource, 42 // and attach an event to it 43 Button button = FindViewById<Button>(Resource.Id.myButton); 44 45 button.Click += delegate { SayHello(button); }; 46 } 47 SayHello(Button button)48 private void SayHello(Button button) 49 { 50 Server server = new Server 51 { 52 Services = { Greeter.BindService(new GreeterImpl()) }, 53 Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) } 54 }; 55 server.Start(); 56 57 // use loopback on host machine: https://developer.android.com/studio/run/emulator-networking 58 //10.0.2.2:50051 59 Channel channel = new Channel("localhost:50051", ChannelCredentials.Insecure); 60 61 var client = new Greeter.GreeterClient(channel); 62 string user = "Xamarin " + count; 63 64 var reply = client.SayHello(new HelloRequest { Name = user }); 65 66 button.Text = "Greeting: " + reply.Message; 67 68 channel.ShutdownAsync().Wait(); 69 server.ShutdownAsync().Wait(); 70 71 count++; 72 } 73 74 class GreeterImpl : Greeter.GreeterBase 75 { 76 // Server side handler of the SayHello RPC SayHello(HelloRequest request, ServerCallContext context)77 public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context) 78 { 79 return Task.FromResult(new HelloReply { Message = "Hello " + request.Name }); 80 } 81 } 82 } 83 } 84 85