using ConsoleChatServer; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace RockPaperScissorsServer { internal class Server { // Attributes const String URL = "server.allcatsaregrey.co.uk"; const int PORT = 19000; static String[] choices = { "rock", "paper", "scissors" }; static Random r = new Random(); static int index = r.Next(choices.Length); static void Main(string[] args) { // Declares networking variables IPAddress ip = IPSorter.FindIPv4Address(URL); TcpListener tcpListener = new TcpListener(ip, PORT); // Shows what IP and Port the server has been started on Console.WriteLine("Starting server..."); tcpListener.Start(); Console.WriteLine($"Started server on host {ip}:{PORT}"); // Begin a loop to listen for incoming connection while (true) { // Accepts an incoming connection Socket client = tcpListener.AcceptSocket(); // Receives the user's name byte[] nameBuffer = new byte[1024]; int nameReceived = client.Receive(nameBuffer, SocketFlags.None); char[] nameChars = new char[nameReceived]; Decoder d = Encoding.UTF8.GetDecoder(); int nameCharLength = d.GetChars(nameBuffer, 0, nameReceived, nameChars, 0); String name = new string(nameChars); // Shows a client has connected Console.WriteLine($"{name} has connected."); // Receives user's choice byte[] clientChoiceBuffer = new byte[1024]; int clientChoiceReceived = client.Receive(clientChoiceBuffer, SocketFlags.None); char[] choiceChars = new char[clientChoiceReceived]; int choiceCharLength = d.GetChars(clientChoiceBuffer, 0, clientChoiceReceived, choiceChars, 0); String c = new string(choiceChars); // Shows the user's choice Console.WriteLine($"{name} has chosen {c}."); // Server chooses rock paper or scissors byte[] serverChoice = Encoding.ASCII.GetBytes(choices[index]); String s = Encoding.UTF8.GetString(serverChoice); Console.WriteLine($"Server has chosen: {s}"); // Informs the client that the server has chosen byte[] serverChoiceBuffer = Encoding.ASCII.GetBytes(s); client.Send(serverChoiceBuffer, SocketFlags.None); // Determine winner if (c == s || s == c) { Console.WriteLine("Tied."); } else if (c == "rock" && s == "scissors" || c == "paper" && s == "rock" || c == "scissors" && s == "paper") { Console.WriteLine($"{name} has won."); } else { Console.WriteLine("Server has won."); } Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } } }