Beispiel #1
0
        public static async Task HandleResponse(TcpClient client, int clientId)
        {
            using (client)
            {
                var stream = client.GetStream();
                using (stream)
                {
                    while (true)
                    {
                        Response response;
                        bool     status = false;
                        try
                        {
                            //serialize received request
                            var request = await ReadRequest(stream)
                                          .WithWaitCancellation(CancellationTokenSource.Token);

                            //log the received request to the console
                            PrintRequest(request, clientId);

                            //send the serialized request to the server
                            response = await _server.ResolveRequest(request);

                            status = response.Status != 200;
                        }
                        catch (OperationCanceledException)
                        {
                            response = status
                                ? ResponseFactory.SuccessResponse("Server shutdown successful.")
                                : ResponseFactory.ServiceUnavailableResponse();
                        }
                        catch (Exception e)
                        {
                            //if an error occurred in the read process, get an error response to give to the client
                            response = ResponseFactory.ServerErrorResponse(e.Message);
                        }

                        //deserialize and send the response to the client
                        await WriteResponse(stream, response);

                        //if the server is in shutdown terminate this client
                        if (!CancellationTokenSource.IsCancellationRequested)
                        {
                            continue;
                        }

                        stream.Close();

                        return;
                    }
                }
            }
        }
Beispiel #2
0
        //method responsible for executing the function requested by the client
        //it chooses one of the available functions inside the _methodResolver structure
        public async Task <Response> ResolveRequest(Request request)
        {
            if (_serverState == ServerState.Offline)
            {
                return(ResponseFactory.ServiceUnavailableResponse());
            }

            bool methodExists = _methodResolver.TryGetValue(request.Method.ToLower(), out var serverOperation);

            if (!methodExists)
            {
                return(ResponseFactory.InvalidRequestResponse("The provided method is not supported."));
            }

            return(await(Task <Response>) serverOperation.DynamicInvoke(request));
        }