Example #1
0
        private static void DoChat()
        {
            DateTime joinTime     = DateTime.Now;
            int      requestCount = 0;
            int      error        = 0;
            string   username     = $"User_{new Random().Next(0, 1000)}";

            Logger.LogQueue.Enqueue($"Client #{_clNo} connected, IP: {_clientSocket.Client.RemoteEndPoint}");
            while (error < 1)
            {
                try
                {
                    requestCount++;
                    string res = NetworkHelper.Receive(_clientSocket.GetStream());
                    //Console.BackgroundColor = ConsoleColor.Red;
                    //Logger.LogQueue.Enqueue($"{_clNo}: {res}");
                    string[] parts = res.Split(' ');
                    switch (parts[0])
                    {
                    case "login":
                        Logger.LogQueue.Enqueue($"Client {_clNo} has authenticated with {parts[1]}:{parts[2]}");
                        username = parts[1];
                        break;

                    case "getchunk":
                        Task.Run(() =>
                        {
                            Chunk ch = TerrainGen.GetChunk(Convert.ToInt32(parts[1]), Convert.ToInt32(parts[2]));
                            while (!ch.Finished)
                            {
                                Thread.Sleep(500);
                            }
                            NetworkHelper.Send(_clientSocket.GetStream(), JsonConvert.SerializeObject(new SaveChunk(ch)));
                        });
                        break;

                    default:
                        Logger.LogQueue.Enqueue($"Received unknown command: {res}");
                        break;
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogQueue.Enqueue("Exception occurred with a client: " + ex.StackTrace);
                    _clientSocket.Close();
                    error++;
                }
            }
        }