Exemplo n.º 1
0
        public void ServeClient(TcpClient socket)
        {
            // "using" automatically frees resources when they're no longer in use. If "using" is not used, they have to be closed manually
            using (var streamReader = new StreamReader(socket.GetStream()))
                using (var streamWriter = new StreamWriter(socket.GetStream()))
                {
                    // Read stream, split it, put in array
                    var clientRequestString = streamReader.ReadLine();
                    var clientRequestArray  = clientRequestString.Split(' ');

                    // Checking for valid syntax
                    if (!clientRequestString.ToLower().Contains("togram") ||
                        !clientRequestString.ToLower().Contains("toounces"))
                    {
                        streamWriter.WriteLine("Command not recognized");
                    }
                    else
                    {
                        // Define index of method and value
                        var requestedMethod = clientRequestArray[0];
                        var valueToConvert  = Convert.ToDouble(clientRequestArray[1]);

                        // Convert to desired type
                        var resultOfConversion = "";
                        if (requestedMethod.ToLower() == "togram")
                        {
                            resultOfConversion = $"{GramsOuncesConversion.OuncesToGrams(valueToConvert)} grams";
                        }
                        if (requestedMethod.ToLower() == "toounces")
                        {
                            resultOfConversion = $"{GramsOuncesConversion.GramsToOunces(valueToConvert)} ounces";
                        }

                        // Place result in outbound stream
                        streamWriter.WriteLine(resultOfConversion);
                    }

                    // Flush result to allow for next
                    streamWriter.AutoFlush = true;
                }
            // If socket is not null (ie. socket is in use), close it
            socket?.Close();
        }
 public void OuncesToGramsCheck()
 {
     Assert.AreNotEqual(100, GramsOuncesConversion.OuncesToGrams(1), 0.00001);
 }
 public void OuncesToGramsNegative()
 {
     GramsOuncesConversion.OuncesToGrams(-10);
 }
 public void GramsToOuncesNegative()
 {
     GramsOuncesConversion.GramsToOunces(-10);
 }
 public void OuncesToGramsSimple()
 {
     Assert.AreEqual(283.4952, GramsOuncesConversion.OuncesToGrams(10), 0.00001);
 }
 public void GramToOuncesSimple()
 {
     Assert.AreEqual(0.3527396195, GramsOuncesConversion.GramsToOunces(10), 0.00001);
 }