using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; using System.Runtime.CompilerServices; namespace Client { internal class Program { // Attributes // Port Number of the server. public const int PORT_NUMBER = 19000; // Define the buffer size. public const int BUFFER_SIZE = 100; // Server host name. public const string HOST_NAME = "localhost"; /// /// Main Method of code for the client. /// /// static void Main(string[] args) { // Establish a TCP Client (this is reliable). TcpClient client = new TcpClient(); // Create an IP end point - this allows for the client to connect to the server. IPAddress myIP = Dns.GetHostAddresses(HOST_NAME)[0]; IPEndPoint remoteEndPoint = new IPEndPoint(myIP, PORT_NUMBER); // Asks the user to input their name. Console.Write("Please enter your name: "); // Display the foreground colour as white. Console.ForegroundColor = ConsoleColor.White; // Store the clients name into a string. string clientName = Console.ReadLine(); // Method to connect the client to the server. client.Connect(remoteEndPoint); // When the client has connected to the server, a message is presented to alert them that it was successful. Console.WriteLine($"{clientName} Sucessfully connected to the server!"); // Network stream - send and recieve data. NetworkStream stream = client.GetStream(); // Message is buffered. byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = stream.Read(buffer, 0, buffer.Length); string message = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine("Received message: " + message); // The while loop is used to allow the user to provide guesses of the number. while (true) { // Allows the user to make a guess as to what the number will be. Console.Write("Please provide a guess: "); // The guess is then stored in a string named 'guess' which is then encoded and sent to the server. string guess = Console.ReadLine(); // The guess that is stored in the string is then send to the server. byte[] guessBytes = Encoding.ASCII.GetBytes(guess); stream.Write(guessBytes, 0, guessBytes.Length); bytesRead = stream.Read(buffer, 0, buffer.Length); message = Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine("Message was recieved: " + message); if (message == "Correct! You win!") { // When the game has finished this message will show. Console.WriteLine("Please press any key to quit."); // When a key is pressed, the application will close. Console.ReadKey(); break; } } } } }