Creating an extremely simple MUD Server in C# using chatGPT.

I've often found myself using chatGPT to start simple projects recently.  Most recently I wasn't happy with any of the open source C# solutions for MUD Servers that exist as they all come with there own schemes for handling a multitude of things I'm not interested in.  Sometimes understand core concepts is easier starting from scratch and building things out on your own.  In the case chatGPT will guide on the creation of a very simple MUD Server.  In fact we will do hardly anything except prompt chatGPT to write a MUD server completely for us.  So if you are wanting a jumping off point for very simple C# MUD Server, this is a pretty good jumping off point if you are looking for something simple.

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MUDServer
{
    public class MUDServer
    {
        private TcpListener listener;
        private List<ClientHandler> clients;

        public MUDServer(string ipAddress, int port)
        {
            IPAddress address = IPAddress.Parse(ipAddress);
            listener = new TcpListener(address, port);
            clients = new List<ClientHandler>();
        }

        public async Task Start()
        {
            listener.Start();
            Console.WriteLine("Server started. Waiting for connections...");

            while (true)
            {
                TcpClient tcpClient = await listener.AcceptTcpClientAsync();
                Console.WriteLine("New client connected.");

                ClientHandler clientHandler = new ClientHandler(tcpClient, this);
                clients.Add(clientHandler);
                Task.Run(() => clientHandler.HandleClient());
            }
        }

        public void BroadcastMessage(string message, ClientHandler excludeClient = null)
        {
            foreach (var client in clients)
            {
                if (client != excludeClient)
                {
                    client.SendMessage(message);
                }
            }
        }

        public void RemoveClient(ClientHandler client)
        {
            clients.Remove(client);
        }
    }

    public class ClientHandler
    {
        private TcpClient tcpClient;
        private NetworkStream stream;
        private MUDServer server;
        private string clientName;

        public ClientHandler(TcpClient tcpClient, MUDServer server)
        {
            this.tcpClient = tcpClient;
            this.server = server;
            stream = tcpClient.GetStream();
        }

        public async Task HandleClient()
        {
            byte[] buffer = new byte[4096];
            int bytesRead;

            await SendMessage("Welcome to the MUD server!");

            try
            {
                while (true)
                {
                    bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
                    string receivedMessage = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                    receivedMessage = receivedMessage.Trim();

                    if (!string.IsNullOrEmpty(receivedMessage))
                    {
                        if (clientName == null)
                        {
                            clientName = receivedMessage;
                            await SendMessage($"Hello, {clientName}! You are now connected.");
                            server.BroadcastMessage($"{clientName} has joined the server.", this);
                        }
                        else
                        {
                            server.BroadcastMessage($"{clientName}: {receivedMessage}", this);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error handling client: {ex.Message}");
            }
            finally
            {
                tcpClient.Close();
                server.RemoveClient(this);
                server.BroadcastMessage($"{clientName} has left the server.");
            }
        }

        public async Task SendMessage(string message)
        {
            byte[] buffer = Encoding.ASCII.GetBytes(message + Environment.NewLine);
            await stream.WriteAsync(buffer, 0, buffer.Length);
        }
    }

    public class Program
    {
        public static async Task Main(string[] args)
        {
            MUDServer server = new MUDServer("127.0.0.1", 8888);
            await server.Start();
        }
    }
}

Then you can ask specific things such as how to broadcast to a certain client.  Or go further and ask it to implement ANSI colors.  So far this has worked great for me starting a simple MUD Server.

public void SendMessageToClient(string message, ClientHandler client)
{
        client.SendMessage(message);
}

 

Comments are closed