Ejemplo n.º 1
0
        private void Connect(string username, string host = "localhost", int port = 1337)
        {
            Debug.Print($"Client Connect: Username='******' Host='{host}' Port='{port}'");

            var channelOptions = new List <ChannelOption> {
                new ChannelOption("GRPC_ARG_KEEPALIVE_TIME_MS", 60 * 1000),
                new ChannelOption("GRPC_ARG_KEEPALIVE_TIMEOUT_MS", 5 * 1000),
                new ChannelOption("GRPC_ARG_HTTP2_MAX_PINGS_WITHOUT_DATA", 0),
                new ChannelOption("GRPC_ARG_KEEPALIVE_PERMIT_WITHOUT_CALLS", 1)
            };

            channel = new Channel($"{host}:{port}", ChannelCredentials.Insecure, channelOptions);

            client = new ChatService.ChatServiceClient(channel);

            var headers = new Metadata();

            headers.Add("username", username);

            try
            {
                call = client.ChatStream(headers);
                var responseHeaders = call.ResponseHeadersAsync.Result;

                if (responseHeaders.GetValue("status") != "OK")
                {
                    throw new Exception("Connection failed");
                }

                toolStripStatusLabel1.Text = "Connected";
                btnConnect.Enabled         = false;
                btnDisconnect.Enabled      = true;

                Task.Run(async() => await ProcessResponseStream()).ContinueWith(t =>
                {
                    if (t.Exception != null)
                    {
                        MessageBox.Show(t.Exception.Message, t.Exception.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    Disconnect();
                }, TaskScheduler.FromCurrentSynchronizationContext());
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.GetType().ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }