Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# multi threaded or multi process?

I have a small question about multithreaded connections between one(Server) to many(Clients) relationship.

My question is:

  • Is my script multi threaded? or Multi process? I have recived some feedback stating that it is multi process?
  • Would each client recieve their stream independently?
  • Id just like to know if this is the correct approach to this.

Here you can see I start to listen to client connections and create a thread for each client connection and I pass the client :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

private void StartListen()
        {
            //Creating a TCP Connection and listening to the port
            tcpListener = new TcpListener(System.Net.IPAddress.Any, 6666);
            tcpListener.Start();
            

            toolStripStatusLabel1.Text = "Listening on port 6666 ...";
            int counter = 0;

            while (true)
            {
                try
                {
                    client = tcpListener.AcceptTcpClient();
                    clientList.Add(client);
                    IPEndPoint ipend = (IPEndPoint)client.Client.RemoteEndPoint;
                    //Updating status of connection
                    toolStripStatusLabel1.Text = "Connected from " + IPAddress.Parse(ipend.Address.ToString());


                    th_inPutStream = new Thread(delegate () { inPutStream(client, counter); });
                    th_inPutStream.Start();

                    counter++;

                }
                catch (Exception err)
                {
                    Cleanup_dep();
                }
            }
        }

  • This is where I handle the client input stream where i pre-process the client input stream:

private void inPutStream(TcpClient client, int clientID)
        {
            try
            {
                while (true)
                {
                    NetworkStream networkstream = client.GetStream();

                    if (networkstream.DataAvailable == true)
                    {
                        int messageID = 0;
                        int messageSize = 0;
                        int bufferSize = 100;

                        //First retrieve size of header
                        byte[] fileSizeBytes = new byte[4];
                        int bytes = networkstream.Read(fileSizeBytes, 0, 4);
                        int dataLength = BitConverter.ToInt32(fileSizeBytes, 0);

                        //Read stream containing header with message details
                        byte[] header = new byte[dataLength];
                        int headerbyte = networkstream.Read(header, 0, dataLength);
                        string headerString = Encoding.ASCII.GetString(header, 0, headerbyte);

                        // Process Message information ie Message ID & Message Size
                        string[] headerSplit = headerString.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                        Dictionary<string, string> headers = new Dictionary<string, string>();
                        foreach (string s in headerSplit)
                        {
                            if (s.Contains(":"))
                            {
                                headers.Add(s.Substring(0, s.IndexOf(":")), s.Substring(s.IndexOf(":") + 1));
                            }
                        }
                        //Fetch Message ID & Size
                        messageSize = Convert.ToInt32(headers["len"]);
                        messageID = Convert.ToInt32(headers["MsgId"]);


                        //Filter actions by Message ID
                        if (messageID == 1)//Machine info
                        {
                            string machineinfo = receiveMessage(messageSize, bufferSize, networkstream);
                            clientNames.Add(machineinfo.Split(new char[] { '\r', '\n' })[0]);
                            updateClientListUI();
                        }
                        if (messageID == 2)//CMD Commands
                        {
                            cmdres = receiveMessage(messageSize, bufferSize, networkstream);
                            activeForm.updateText(cmdres);
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Cleanup_dep();
            }

        }

Thanks in advance.

>Solution :

  • Since you are using Thread and not Process I don’t see any indication as to why this would be a multi process approach.

  • Without knowing how TcpClient.GetStream is exactly implemented, I would be suprised if the call on one client would have anything to do with the same call on another client. Other than obvious, unavoidable, coherences like sharing the same bandwidth if the connections are accepted on the same nic of course.

  • Depends on what you are trying to do. If this is for work, I would question if there isn’t an existing solution you could use. If this is for education there are a few improvements that come to mind:

    • use async and Task instead of Thread is usually recommended
    • using var networkstream = client.GetStream(); will make sure the stream is disposed of correctly
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading