Feature Post

Top

Simplest console based client/server program

For those who want a quick and easy way to grasp the client/server model.

class Program
{
    static void Main(string[] args)
    {
        bool sender = false;
        if (args.Length > 0) sender = true;
        if (sender)
        {
            try
            {
                Console.WriteLine("..:: Client ::..");
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5000);
                sock.Connect(ipe);
                while (true)
                {
                    string toSend = Console.ReadLine();
                    sock.Send(Encoding.UTF32.GetBytes(toSend));
                    Console.WriteLine("Sent.");
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
        else
        {
            try
            {
                Console.WriteLine("..:: Server ::..");
                IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 5000);
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

                sock.Bind(ipe);
                sock.Listen(4);
                int nCount = 0;
                while (true)
                {
                    nCount++;
                    Socket newSock = sock.Accept();
                    if (!newSock.Connected) continue;
                    else
                    {
                        byte[] buffer = new byte[1024];//Can pull from a central config file
                        if (newSock.Receive(buffer) > 0) { Console.WriteLine("Received:"); Console.WriteLine(Encoding.UTF32.GetString(buffer)); }
                        newSock.Close();
                    }
                }
            }
            catch (SocketException e)
            {
                Console.WriteLine(e.Message);
                Console.ReadLine();
            }
        }
}

Usually, almost always, you send the number of bytes before sending the actual text, so that the other side would know how much data to expect.

Happy coding!