Main Site Documentation

TCP socket connection questions


#1

I have been trying out my new wings by starting out simple and create a TCP socket server on port 23.
My goal for now is to open a telnet client and connect to my Cobra board and simply echo back what i receive. With the examples here that made starting out easy.

The only thing i am trying to figure out is if i need to put a Thread.Sleep in that main loop to allow other threads to run.

So i have the following code that i snagged from there and there and changed it.
after the socket is accepted it calls ProcessRequest()


        private void ProcessRequest()
        {
            const Int32 c_microsecondsPerSecond = 1000000;

            // 'using' ensures that the client's socket gets closed.
            using (m_clientSocket)
            {
                // Wait for the client request to start to arrive.

                Debug.Print("Connected...");
                byte[] buffer;

                while (Ethernet.IsCableConnected)
                {
                    if (m_clientSocket.Poll(5 * c_microsecondsPerSecond, SelectMode.SelectRead))
                    {
                        if (m_clientSocket.Available > 0)
                        {
                            buffer = new byte[m_clientSocket.Available];
                            m_clientSocket.Receive(buffer);

                            m_clientSocket.Send(buffer);
                        }
                        else
                        {
                            Debug.Print("No Data, Connection Lost.");
                            break;
                        }
                    }
                    else
                    {

                        Debug.Print("Received Data Timed Out, Closing Connection");
                        break;
                    }
                }
            }
        }



#2

As a general rule, unless you have a really good reason not to always put a Thread.Sleep() in any loop that may run for any noticeable time. Otherwise, you’ll end up in a point where you can no longer debug and other threads can’t do anything.


#3

Thank you.