Socket.connect does not work SocketException : 10054

here is the scenario :

1- I read contents of a text file from a flash memory plugged into the usb host module

2- I want to send the read text file contents using TCP to a windows forms application which is a TCP Listener

here is the code to send TCP running on FEZ device :

 public bool SendFile()
            bool returnValue = false;
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ServerIP = new IPAddress(new byte[] { 172, 16, 43, 193 });
                IPEndPoint ServerEndPoint = new IPEndPoint(ServerIP, 12241);
                byte[] buf = Encoding.UTF8.GetBytes(FileContentText);
                if (socket.Poll(5 * 1000000, SelectMode.SelectRead)) // wait for data from the server
                    byte[] inbuf = new byte[socket.Available];
                    //string m = new string(Encoding.UTF8.GetChars(inbuf));

            catch (Exception ex)
                string s = ex.Message;
                if (ex.InnerException != null)
                    s = s + ex.InnerException.Message;
                if (ex.StackTrace != null)
                    s = s + ex.StackTrace;
            return returnValue;

and here is the code on my windows forms application :

private void Form1_Load(object sender, EventArgs e)
                System.Threading.Thread t = new Thread(new ThreadStart(SendTCPMessage));
                txtStatus.Text = txtStatus.Text + "TCP listening established successfully\r\n";
            catch (Exception ex)
                txtStatus.Text = txtStatus.Text + "An error occured while trying to establish TCP listening : \r\n" + ex.Message + "\r\n";
                if (ex.InnerException != null)
                    txtStatus.Text = txtStatus.Text + ex.InnerException + "\r\n";

        private static void SendTCPMessage()
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, c_port);
            while (true)
                // Wait for a client to connect.
                Socket clientSocket = server.Accept();
                // Process the client request. true means asynchronous.
                new ProcessClientRequest(clientSocket, true);

The issue is that on the FEZ device at the following line of code :


the application throws the following exception :

ex.Message :
Exception was thrown:

ex.StackTrace :
Exception was thrown:

Any helps would be appreciated

and here is the code for in my win form app :

        internal sealed class ProcessClientRequest

            private Socket m_clientSocket;
            /// <summary>
            /// The constructor calls another method to handle the request, but can
            /// optionally do so in a new thread.
            /// </summary>
            /// /// <param name="clientSocket"></param>
            /// <param name="asynchronously"></param>
            public ProcessClientRequest(Socket clientSocket, Boolean asynchronously)
                m_clientSocket = clientSocket;
                if (asynchronously)
                    // Spawn a new thread to handle the request.
                    new Thread(ProcessRequest).Start();
                else ProcessRequest();
            /// <summary>
            /// Processes the request.
            /// </summary>

            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.
                    Byte[] buffer = new Byte[1024];
                    if (m_clientSocket.Poll(5 * c_microsecondsPerSecond,
                        // If 0 bytes in buffer, then the connection has been closed,
                        // reset, or terminated.
                        if (m_clientSocket.Available == 0)
                        // Read the first chunk of the request (we don't actually do
                        // anything with it).
                        Int32 bytesRead = m_clientSocket.Receive(buffer,
                        m_clientSocket.Available, SocketFlags.None);
                        String result = "";
                        string FileContent = new string(Encoding.UTF8.GetChars(buffer));
                        MessageBox.Show("Text file with following content received :\r\n" + FileContent);
                        if (SaveFile(FileContent))
                            result = "1";
                            result = "0";

                        // Return a static string to the client.        
                        byte[] buf = Encoding.UTF8.GetBytes(result);
                        int offset = 0;
                        int ret = 0;
                        int len = buf.Length;
                        while (len > 0)
                            ret = m_clientSocket.Send(buf, offset, len, SocketFlags.None);
                            len -= ret;
                            offset += ret;

            private bool SaveFile(string FileContent)
                bool returnValue = false;
                    string RootSaveDirectory = ConfigurationManager.AppSettings["FileSaveRootDirectory"].ToString();
                    string SaveDirectoryName = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "   " + DateTime.Now.Hour.ToString() + "." + DateTime.Now.Minute.ToString() + "." + DateTime.Now.Second.ToString() + "." + DateTime.Now.Millisecond.ToString();
                    string SaveDirectory = Path.Combine(RootSaveDirectory, SaveDirectoryName);
                    if (!Directory.Exists(SaveDirectory))
                    string FileName = ConfigurationManager.AppSettings["FileName"].ToString();
                    File.WriteAllText(Path.Combine(SaveDirectory, FileName), FileContent);
                    returnValue = true;
                catch { }
                return returnValue;

SocketException as a member with the error code.
Then google "SocketException " to get a closer description of the problem.
It also would be interesting if the exception is thrown immediately or after a timeout.

More infos you could provide:
What type of board and Ethernet module are you using
Which firmware version.
How does your network init code look like.

@ Reinhard Ostermeier -

The SocketException Id is : 10054

firmware version 2013R2

10054 = connection reset by peer.

@ Brett -
I am a little new to socket programming
could you guide me more specific please

connection reset by peer means that the other side (your win forms app) closed the connection unexpected.
This could be if your app crashes or you stop it with debugger (breakpoint is usually no problem).

I’m missing 2 things in you win forms app.
(Thread) t.Start() and the code from ProcessClientRequest.

If thread would not be started I would expect thet you get a connection timeout, because no one is listening.

if ProcessClientRequest for example closes the socket this could cause the exception you see.

I also would not exclude any firewall related issues.

1 Like

@ Reinhard Ostermeier -

I added the code for ProccessClientRequest

I have also turned my firewall off , and still get that error

I made the experience that if you call send immediately followed by a close on a socket, that the socket is closed before the data is fully transmitted to the other side.
A solution would be to keep the socket open until it’s closed from the other side.
But this does not tell us why you get this exception on Connect.
Have you ever put a breakpoint after the accept on win forms side?
If it’s hit the connection is established. Then step through the code to see where the exception happens (after receive, after send, …
If it works when stepping through the code then it’s a timing problem, may be the one I mentioned above.

I got the issue !
I have forgotten to write :

after :

```cs]System.Threading.Thread t = new Thread(new ThreadStart(SendTCPMessage));[/code

that was a great catch then @ Reinhard !

What I do not really understand is the error code karamafrooz got!?
‘connection reset by peer’ I would think that connection was established, but interrupted then.
If no one listens to the port I would think you get something like ‘connection rejected’ at least that’s the error message I get when I try to connect from win .net and no one listens.