Blocking Sockets Server using C#

In this example we have a Blocking Sockets Server C# code example

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;

    public class Server
    {
        public void Serve(IPAddress address, int port)
        {
            ThreadPool.SetMinThreads(50, 50); // Refer to Chapter 21
            ThreadPool.SetMaxThreads(50, 50); // Refer to Chapter 21
            TcpListener listener = new TcpListener(address, port);
            listener.Start();
            while (true)
            {
                TcpClient c = listener.AcceptTcpClient();
                ThreadPool.QueueUserWorkItem(this.Accept, c);
            }
        }

        private void Accept(object clientObject)
        {
            using (TcpClient client = (TcpClient)clientObject)
            using (NetworkStream n = client.GetStream())
            {
                byte[] data = new byte[5000];

                int bytesRead = 0;
                int chunkSize = 1;
                while (bytesRead < data.Length && chunkSize > 0)
                {
                    bytesRead += chunkSize = n.Read(data, bytesRead, data.Length - bytesRead); // BLOCKS
                }

                Array.Reverse(data);
                n.Write(data, 0, data.Length); // BLOCKS
            }
        }
    }

You can download all the Asynchronous Methods code examples here



Comments

No comments yet.

Add Yours

  • Author Avatar

    YOU


Comment Arrow




About Author

Robert

Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning hands down.