• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

C# tcp server can only handle one client?...

#1
Hey there,

i'm working on a tcp server that can handle many clients. Its written in c# async and callbacks. So i'm finished but the server can only handle one connection... Somewehre contains an error but after 3 days of search i don't know where. i will paste the code. Funny: The client doesn't throw any errors. The server shows only one connected client. And other clients can't connect.

Code:
    public class StateObject
    {
        public Socket WorkSocket;
        public const int BufferSize = 32;
        public byte[] Buffer = new byte[BufferSize];
        public StringBuilder Sb = new StringBuilder();
    }
    internal class TcpServer
    {
        public static Socket ServerSocket;
        public static List<SimClient> LbConnections = new List<SimClient>();

        public static async void StartTcpServerAsync()
        {
            try
            {
                await Task.Run(() =>
                {
                    ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    LbConnections = new List<SimClient>();
                    var serverIp = new IPEndPoint(IPAddress.Parse(Settings.Default.IPAddress), Settings.Default.Port);

                    ServerSocket.Bind(serverIp);
                    ServerSocket.Listen(0);
                    InitServer.IsServerReady = true;

                    ServerSocket.BeginAccept(AcceptCallback, ServerSocket);
                });
            }
            catch (Exception e)
            {
                AdvancedLogging.WriteLog(e.Message + "(" + e.InnerException + ")", 2);
                InitServer.IsServerReady = false;
            }
        }

        private static void AcceptCallback(IAsyncResult result)
        {
            var listener = (Socket)result.AsyncState;
            var handler = listener.EndAccept(result);

            var state = new StateObject();
            state.WorkSocket = handler;

            LbConnections.Add(new SimClient { State = state });
            handler.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
        }

        private static void ReceiveCallback(IAsyncResult result)
        {
            var state = (StateObject)result.AsyncState;
            var socket = state.WorkSocket;
            var received = socket.EndReceive(result);

            if (received <= 0)
            {
                socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
                return;
            }

            state.Sb.Append(Encoding.ASCII.GetString(
                state.Buffer, 0, received));

            var content = state.Sb.ToString();
            if (content.IndexOf("<EOF>", StringComparison.Ordinal) > -1)
            {
                DataHandler.HandleData(content.Substring(0, content.Length - 5), state);
                state.Sb.Clear();
                socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
            }
            else
            {
                socket.BeginReceive(state.Buffer, 0, StateObject.BufferSize, SocketFlags.None, ReceiveCallback, state);
            }
        }
    }
 

ddawson

Resource contributor
#2
I don't read a whole lot of C#, but I do know that each connection to the server has to be handled by a separate thread. Your main thread will listen for the connections and will hand the responsibility for responding off to a new thread. The new thread will terminate once it completes the response to the client request.