Exemple #1
0
        public static async Task Main(string[] args)
        {
            const int    port       = 50051;
            const string clientName = "Super user";

            Channel channel = new Channel("localhost", port, ChannelCredentials.Insecure);

            var client = new Chat.ChatClient(channel);

            while (true)
            {
                Console.WriteLine(@"Type a message to send, type exit to quit");
                string input = Console.ReadLine();
                if (input.ToLower().Equals("exit"))
                {
                    break;
                }
                var reply = await client.GetMessageAsync(new ClientHello { ClientName = clientName, ClientMessage = input });

                Console.WriteLine($@"Message from Server: {reply.ServerName} - {reply.ServerNumber}: {reply.ServerMessage}");
            }

            await channel.ShutdownAsync();

            Console.WriteLine("Press any key to exit...");
        }
        static async Task Main(string[] args)
        {
            var channel = GrpcChannel.ForAddress("https://localhost:5001");

            _client = new Chat.ChatClient(channel);

            var userName = await SignInAsync();

            var roomId = await ChooseRoomAsync();

            var cancel     = new CancellationTokenSource();
            var listenTask = Task.Run(() => ListenAsync(roomId, userName, cancel.Token));

            Console.WriteLine("Enter /q to quit.");

            while (true)
            {
                Console.Write("> ");
                var line = Console.ReadLine();
                if (line?.Trim() == "/q")
                {
                    break;
                }
                if (!string.IsNullOrWhiteSpace(line))
                {
                    await _client.SayAsync(new SayRequest { RoomId = roomId, UserName = userName, Message = line });
                }
            }

            cancel.Cancel();
            await listenTask;
        }
Exemple #3
0
        public ChatServiceClient()
        {
            // Locate required files and set true to enable SSL
            var secure = false;

            if (secure)
            {
                // create secure channel
                var serverCACert = File.ReadAllText(@"C:\localhost_server.crt");
                var clientCert   = File.ReadAllText(@"C:\localhost_client.crt");
                var clientKey    = File.ReadAllText(@"C:\localhost_clientkey.pem");
                var keyPair      = new KeyCertificatePair(clientCert, clientKey);
                var credentials  = new SslCredentials(serverCACert, keyPair);

                // Client authentication is an option. You can remove it as follows if you only need SSL.
                //var credentials = new SslCredentials(serverCACert);

                m_client = new Chat.ChatClient(
                    new Channel("localhost", 50052, credentials));
            }
            else
            {
                // create insecure channel
                m_client = new Chat.ChatClient(
                    new Channel("localhost", 50052, ChannelCredentials.Insecure));
            }
        }
Exemple #4
0
 public static void RemoveChatClient(Chat.ChatClient chatClient)
 {
     if (ChatClients.ContainsKey(chatClient.GameSession.Player.Id))
     {
         chatClient.GameSession.Chat = null;
         ChatClients.TryRemove(chatClient.GameSession.Player.Id, out chatClient);
     }
 }
Exemple #5
0
        public Chater(string name, string target = "127.0.0.1:4001")
        {
            Name    = name;
            Target  = target;
            channel = new Channel(Target, ChannelCredentials.Insecure);

            client = new Chat.ChatClient(channel);
        }
Exemple #6
0
 public static void AddChatClient(Chat.ChatClient chatClient)
 {
     if (ChatClients.ContainsKey(chatClient.GameSession.Player.Id))
     {
         return;
     }
     chatClient.GameSession.Chat = chatClient;
     ChatClients.TryAdd(chatClient.GameSession.Player.Id, chatClient);
 }
Exemple #7
0
        static async Task Main(string[] args)
        {
            var httpHandler = new HttpClientHandler();
            // Return `true` to allow certificates th at are untrusted/invalid
            //httpHandler.ServerCertificateCustomValidationCallback =
            //    HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;

            //var channel = GrpcChannel.ForAddress(new UriBuilder("https://127.0.0.1:5001").Uri);
            var channel = GrpcChannel.ForAddress("https://*****:*****@mercury.com", UserTag = "papu", UserId = 3
                        },
                        Text      = result,
                        Timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd hh:mm:ss")
                    },
                    UserId = 1
                });
            }

            Console.WriteLine("Disconnecting");
            await request.RequestStream.CompleteAsync();

            await readTask;

            Console.ReadKey();
        }
Exemple #8
0
        static async Task Main(string[] args)
        {
            var clientCertificate = new X509Certificate2("client.pfx", "secretsquirrel");

            var handler = new HttpClientHandler
            {
                ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) =>
                {
                    Console.WriteLine(certificate2.Issuer);
                    Console.WriteLine(clientCertificate.Issuer);
                    return(certificate2.Issuer == clientCertificate.Issuer);
                }
            };

            handler.ClientCertificates.Add(clientCertificate);

            var http = new HttpClient(handler);

            var channel = GrpcChannel.ForAddress("https://localhost:5001", new GrpcChannelOptions
            {
                HttpClient = http
            });

            _client = new Chat.ChatClient(channel);

            var token = await SignInAsync();

            http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);

            var roomId = await ChooseRoomAsync();

            var cancel     = new CancellationTokenSource();
            var listenTask = Task.Run(() => ListenAsync(roomId, cancel.Token));

            Console.WriteLine("Enter /q to quit.");

            while (true)
            {
                Console.Write("> ");
                var line = Console.ReadLine();
                if (line?.Trim() == "/q")
                {
                    break;
                }
                if (!string.IsNullOrWhiteSpace(line))
                {
                    await _client.SayAsync(new SayRequest { RoomId = roomId, Message = line });
                }
            }

            cancel.Cancel();
            await listenTask;
        }
 public static void AcceptCallback(IAsyncResult ar)
 {
     try
     {
         AllDone.Set();
         var listener   = (Socket)ar.AsyncState;
         var handler    = listener.EndAccept(ar);
         var chatClient = new Chat.ChatClient(handler);
     }
     catch (Exception e)
     {
         Out.WriteLine(e.Message, "ChatServer ERROR");
     }
 }
Exemple #10
0
        private static async Task SendMessage(GrpcChannel channel, string Name, string Message)
        {
            var ChatClient2 = new Chat.ChatClient(channel);
            var test2       = ChatClient2.ChatStram();

            //定义接收响应逻辑

            var ChatRespTask = Task.Run(async() =>
            {
                while (await test2.ResponseStream.MoveNext())
                {
                    var response = test2.ResponseStream.Current;
                    Console.WriteLine($"{response.Message}");
                }

                /*    await foreach (var resp in test2.ResponseStream.ReadAllAsync())
                 *  {
                 *      Console.WriteLine(resp.Message);
                 *  }*/
            });


            ChatRequest chatRequest = new ChatRequest()
            {
                Name = Name, Message = Message
            };
            //发送完毕
            await test2.RequestStream.WriteAsync(chatRequest);

            await test2.RequestStream.CompleteAsync();

            // Console.WriteLine(test2.ResponseStream.ReadAllAsync().GetAsyncEnumerator().Current.Message);

            //开始接收响应
            await ChatRespTask;

            //await Listening(channel);
            Message = Console.ReadLine();
            if (!Message.Equals("Bye"))
            {
                await SendMessage(channel, Name, Message);
            }
            else
            {
                Console.WriteLine("结束");
            }
        }
Exemple #11
0
    private void Auth()
    {
        channel = new Channel(ip + ":" + port, ChannelCredentials.Insecure);
        client  = new Chat.ChatClient(channel);

        var req = new RequestAuthorize();

        req.Name = userName;

        try {
            var res = client.Authorize(req);
            sid = res.SessionId;
        }
        catch (RpcException e) {
            Debug.Log(ExceptionMsg(e));
            return;
        }


        Task.Run(() => Connect());
    }
Exemple #12
0
        public static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var httpClientHandler = new HttpClientHandler();

            // Return `true` to allow certificates that are untrusted/invalid
            //忽略无效证书(可行)
            //既然是证书无效导致的问题,那么忽略无效证书是不是可以呢?在代码中加上忽略无效证书的代码。然后再次进行尝试发现也是可以的。
            //不过这里需要注意的是这个忽略无效证书在开发过程中使用即可,换到生产环境还是替换成有效证书
            httpClientHandler.ServerCertificateCustomValidationCallback =
                HttpClientHandler.DangerousAcceptAnyServerCertificateValidator;
            var httpClient = new HttpClient(httpClientHandler);
            var channel    = GrpcChannel.ForAddress("https://192.168.8.100:5001", new GrpcChannelOptions {
                HttpClient = httpClient
            });

            /*            AppContext.SetSwitch(
             *    "System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);*/
            //  var channel = GrpcChannel.ForAddress("https://localhost:5001");

            var    ChatClient2 = new Chat.ChatClient(channel);
            var    chat        = ChatClient2.join();
            string Name        = "";

            if (Name.Equals(""))
            {
                Console.WriteLine("输入用户名:");
                Name = Console.ReadLine();
            }
            Console.WriteLine("输入消息:");
            string Message = "";

            Message = Console.ReadLine();

            //定义接收响应逻辑
            _ = Task.Run(async() =>
            {
                while (await chat.ResponseStream.MoveNext(cancellationToken: CancellationToken.None))
                {
                    var response = chat.ResponseStream.Current;
                    Console.WriteLine($"{response.Name}:{response.Message}");
                }

                /*              await foreach (var resp in chat.ResponseStream.ReadAllAsync())
                 *            {
                 *                Console.WriteLine(resp.Message);
                 *            }*/
            });

            await chat.RequestStream.WriteAsync(new ChatRequest { Name = Name, Message = $"{Name} has joined the room" });

            string line;

            while ((line = Console.ReadLine()) != null)
            {
                if (line.ToLower() == "bye")
                {
                    break;
                }
                await chat.RequestStream.WriteAsync(new ChatRequest { Name = Name, Message = line });
            }
            await chat.RequestStream.CompleteAsync();

            // await SendMessage(channel, Name, Message);

            Console.ReadKey();
        }
Exemple #13
0
 public ServerApiConsumer(IMapper iMapper, Chat.ChatClient chatClient)
 {
     this.iMapper    = iMapper ?? throw new ArgumentNullException(nameof(iMapper));
     this.chatClient = chatClient ?? throw new ArgumentNullException(nameof(chatClient));
 }