Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 1069939
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 16, 20262026-05-16T20:29:36+00:00 2026-05-16T20:29:36+00:00

I have build a basic .NET server-client infrastructure using TcpListener and SocketClient. It is

  • 0

I have build a basic .NET server-client infrastructure using TcpListener and SocketClient.
It is multithreaded and asynchronious. The problem is, that the server crashes at some point when over 30 clients are connected at once.

I could not yet locate the cause for the crashes though I do use quite a few Try-Catch blocks to make sure to log all excepions.

So I’m thinking, I may be doing something wrong conceptually in the server code. I hope you guys can help me find the cause for those crashes. The code is the following:

Starting server and listening for a connection:

 public void StartServer()
    {
        isConnected = true;
        listener.Start();
        connectionThread = new Thread(new ThreadStart(ListenForConnection));
        connectionThread.Start();
    }

    private void ListenForConnection()
    {
        while (isConnected)
        {
            try
            {
                TcpClient client = listener.AcceptTcpClient();
                ClientConnection connection = new ClientConnection(this, client);
                connections.Add(connection);
            }
            catch (Exception ex)
            {
                log.Log("Exception in ListenForConnection: " + ex.Message, LogType.Exception);
            }
        }
    }

The ClientConnection class:

 public class ClientConnection : IClientConnection
{
    private TcpClient client;
    private ISocketServer server;
    private byte[] data;
    private object metaData;

    public TcpClient TcpClient
    {
        get { return client; }
    }

    internal ClientConnection(ISocketServer server, TcpClient client)
    {
        this.client = client;
        this.server = server;

        data = new byte[client.ReceiveBufferSize];

        lock (client.GetStream())
        {
            client.GetStream().BeginRead(data, 0, client.ReceiveBufferSize, ReceiveMessage, null);
        }
    }

    internal void ReceiveMessage(IAsyncResult ar)
    {
        int bytesRead;

        try
        {
            lock (client.GetStream())
            {
                bytesRead = client.GetStream().EndRead(ar);
            }

            if (bytesRead < 1)
                return;

            byte[] toSend = new byte[bytesRead];
            for (int i = 0; i < bytesRead; i++)
                toSend[i] = data[i];

            // Throws an Event with the data in the GUI Dispatcher Thread
            server.ReceiveDataFromClient(this, toSend);

            lock (client.GetStream())
            {
                client.GetStream().BeginRead(data, 0, client.ReceiveBufferSize, ReceiveMessage, null);
            }
        }
        catch (Exception ex)
        {
            Disconnect();
        }
    }

    public void Disconnect()
    {
        // Disconnect Client
    }


}

And sending data from the server to one or all clients:

public void SendDataToAll(byte[] data)
    {
        BinaryWriter writer;

        try
        {
            foreach (IClientConnection connection in connections)
            {
                writer = new BinaryWriter(connection.TcpClient.GetStream());
                writer.Write(data);
                writer.Flush();
            }
        }
        catch (Exception ex)
        {
            // Log
        }
    }

    public void SendDataToOne(IClientConnection client, byte[] data)
    {
        BinaryWriter writer;

        try
        {
            writer = new BinaryWriter(client.TcpClient.GetStream());
            writer.Write(data);
            writer.Flush();
        }
        catch (Exception ex)
        {
            // Log
        }
    }

At some point the server crashes and I really got no starting point where to even look for the problem. If needed I can provide more code.

Any help is very appreciated 🙂
Andrej

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-16T20:29:37+00:00Added an answer on May 16, 2026 at 8:29 pm

    You should make access to the connections field thread safe.

    In SendData, you are iterating over connections and sending data to each client. If a new client connects when the foreach loop is executing, you will get an exception with the message “Collection was modified; enumeration operation may not execute” since the collection is modified while you are iterating over it which is not allowed.

    Modify the line in SendDataToAll to

    foreach (IClientConnection connection in connections.ToList())
    

    to make the problem go away (solution is courtesy of Collection was modified; enumeration operation may not execute).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have build a webapplication using ASP.NET MVC and JQuery. On my local machine
I currently have a TCP server application written in .Net that receives and submits
I have build C# program that work with RAPI (communication to PPC or WinCE)
I have build a c# class library verification.dll using OpenCVSharp. This references OpenCvSharp.dll in
I work for an agency that has been responsible for maintaining a client’s .net
I have an ASP.NET MVC application, with some RESTful services that I'm trying to
I am using the built-in forms authentication that comes with asp.net mvc. I added
I’m trying to write a basic ASP.NET form (using Visual Studio 2010) to submit
I have a requirement to build features that perform certain background tasks on a
I have a .NET 4.0 console application running on a production server. The app

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.