Socket.connect hangs/bug EMX?

@ T_Langholen -

Yes, thread wrapper is better.

I think I have the same problem with ExecutionConstraint.Install(…). For some reason the device reboots after a number of ExecutionConstraintExceptions or socket.connect(). Does the threadwrapper approach solve this problem?

@ andre.m
Ok. Do you think you could provide an example of an threadwrapper that is using the httpwebrequest and response classes? I tried to make an implementation but I could not get it to work properly.

Thanks in advance.

I have made my own implementation of a threadwrapper (sett the code below). This, however, does not solve the problem. For some reason my device (G120) restarts after a while due to the failure of opening sockets.


			HttpWebResponse resp = null;
			
			try
			{
				var thread = new Thread(() => { resp = request.GetResponse() as HttpWebResponse; });
				thread.Start();
				var completed = thread.Join(20*1000);
				if (!completed) {
					thread.Abort();
					throw new Exception();
				}
			}

@ ollengenic -

How about these:


    public class MySocket
    {
        private Socket _socket;
        private Thread _myThread;
        private EndPoint _remoteEP;
        private Boolean isSocketConnected = false;
        private int _connectTimeOut = 15000; // 15 second


        public MySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            _socket = new Socket(addressFamily, socketType, protocolType);
        }
        ~MySocket()
        {
            // Destroy
        }
        public int TimeOutConnection
        {
            get { return _connectTimeOut; }
            set { _connectTimeOut = value; }
        }
        public Socket GetSocket
        {
              get { return _socket; }
        }
        private void CancelRequestConnect()
        {
            if (_myThread != null)
            {
                try
                {
                    if (_myThread.IsAlive || _myThread.ThreadState == ThreadState.Running)
                    {
                        try
                        {
                            _myThread.Abort();
                        }
                        catch
                        {

                        }
                    }
                    _myThread = null;
                }
                catch
                {
                }
            }
        }
        public Boolean Connect(EndPoint remoteEP)
        {
            CancelRequestConnect();
            _remoteEP = remoteEP;
            isSocketConnected = false;
            _myThread = new Thread(Connect);
            _myThread.Start();
            int timeout = _connectTimeOut;
            while (timeout > 0)
            {
                Thread.Sleep(10);
                timeout -= 10;
                if (isSocketConnected == true) 
                    break;

            }
            if (timeout == 0) // expired
            {
                CancelRequestConnect();
            }

            return isSocketConnected;
        }
        private void Connect()
        {
            _socket.Connect(_remoteEP);
            isSocketConnected = true;
        }


    }



usage:


MySocket socket = new MySocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);
                socket.TimeOutConnection = 5000;
                if (socket.Connect(endPoint))
                {
                    Debug.Print("Connected!");
                }
                else
                {

                    Debug.Print("Failed!");
                }

@ Dat

Thank you! Will try it on monday. By the way, do you have any clue on why the (my) device is restarting itself? It does not seem to be memory related…

@ ollengenic - Maybe an MCU internal Watchdog ?

@ ollengenic -
it is hard to say because we don’t see your code fully :)))

  • it maybe you are opening many sockets and some of them can not be destroyed.
  • or something related to Thread.Join(), WaitOne. For me these methods are hard to debug, that why I used wapper class above then it is easier for debugging or implement more functions (like Accept)

maybe :)))

@ Dat

I have tried your socket implementation and so far the device has not reset itself.

yeb, that code looks like long but in fact it is simple and should not cause to reset the board :))

I still have issues with this bug, its annoying…

I have tried two different wrapper approaches and both fail after some time.
The last I tried is the solution described by @ Dat.

After some time I get an exception in the constructor.
An unhandled exception of type ‘System.Net.Sockets.SocketException’ occurred in Microsoft.SPOT.Net.dll

        public MySocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
        {
            _socket = new Socket(addressFamily, socketType, protocolType);
-	        }

The caller is:

                IPAddress hostIP = IPAddress.Parse(serverName);
                IPEndPoint ep = new IPEndPoint(hostIP, serverPort);

                while (hostSocket == null)
                {
                    MySocket socket = new MySocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    socket.TimeOutConnection = 5000;
                    if (socket.Connect(ep))
                    {
                        EMX_Application1.Program.SystemLog("\r\nConnected to BT Host!", true);
                        hostSocket = socket.GetSocket;
                    }
                    else
                    {

                        EMX_Application1.Program.SystemLog("\r\nFailed To connect to BT Host!", true);
socket = null;
                    }

                    //hostSocket = ConnectSocket(serverName, serverPort);
                }

This is runing in its own threed and inside a while(1) loop.

Basically I try to get a connection, if not connected retry. It may be that I use all the sockets?
I try to destroy the socket object by setting it to null but that does not seem work.

Any idea or suggestions?

@ T_Langholen -

What firmware are you using?

Try to use “try catch”. My code at post#43 very ugly, you can modify it to make it smoother.

@ Dat have tried a try{} and catch but it is stuck in that state so I never get a new socket from the underlying system. I suspect that all the used sockets are not cleaned out so the system runs out of resources.
Tried to add a _socekt.close() in the timout if but that didnt sit well, keep crashing (register dump)
This is a simple basic socket function; it is frankly disturbing that it is not fixed in the core if you ask me, ASAP.

Can someone confirm that this is fixed in 4.3?

my Firmware ver, using EMX:

Pinging… TinyCLR
DeviceInfo:
HAL build info: 4.2.0.0, Microsoft Copyright (C) Microsoft Corporation. All rig
OEM Product codes (vendor, model, SKU): 255, 0, 65535
Serial Numbers (module, system):
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
Solution Build Info: 4.2.10.1, Copyright (C) GHI Electronics, LLC
AppDomains:
default, id=1
Assemblies:
mscorlib,4.2.0.0
Microsoft.SPOT.Native,4.2.0.0
Microsoft.SPOT.Security.PKCS11,4.2.0.0
System.Security,4.2.0.0
Microsoft.SPOT.IO,4.2.0.0
Microsoft.SPOT.Hardware.SerialPort,4.2.0.0
GHI.Premium.IO,4.2.10.0
Microsoft.SPOT.Graphics,4.2.0.0
Microsoft.SPOT.Hardware,4.2.0.0
DI Dual Reader,1.0.0.0
GHI.Premium.System,4.2.10.0
System,4.2.0.0
GHI.Premium.Net,4.2.10.0
System.IO,4.2.0.0
Microsoft.SPOT.Net,4.2.0.0
GHI.Premium.Hardware,4.2.10.0
GHI.Hardware.EMX,4.2.10.0
GHI.Premium.SystemUpdate,4.2.10.0

@ T_Langholen - Can you try to set a socket option:

Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.ReuseAddress, true);

@ T_Langholen -

try 4.2.11.0 please

@ Dat,

Can you please provide a link to where I can find it? I have problem navigating to latest firmware, even google dont give a good link. Thanks…

@ T_Langholen -

https://www.ghielectronics.com/download/sdk/4/netmf-and-gadgeteer-package-2013-r2

Thanks @ Dat, wil try it, quite new one so no wonder I missed it.

However on my current ver I have found the following:
It is now clear that the code uses all the sockets and it takes many minutes before any of them are cleaned out. If I force the GC (not recommended though) it clears out and sockets are released. When socket are used up my web server and telnet server code also hangs before a socket is cleared up. UDP and ICMP works so it is concentrated to a TCP issue.

If a socket connect, hangs forever and the wrapper times out, I get a full system crash when trying to close the hanging socket.

But I will give the latest SDK a go and we will see if that helps.

@ RobvanSchelven -
Socket option didnt help anything, unfortunately but thanks for the suggestion.