15
Vote

Socket.Connect Hangs Forever

description

If you create a new socket and attempt to connect to an invalid IP connect will never timeout or throw an exception.

comments

ZachLibby wrote Nov 16, 2012 at 3:55 PM

Could you please list the device and version of the .NET Micro Framework? If you are experiencing this on a device that uses the RTIP network stack, you will need to work with the board vender to get a resolution. We do not own nor do we have access to the source code for RTIP.

Thanks,
Zach

wrote Feb 22, 2013 at 12:45 AM

ahmedfme wrote Mar 11, 2013 at 6:58 AM

i am facing the same problem and can't solve it , any help appreciated.

Pinging... TinyCLR
HalSystemInfo.halVersion: 4.2.0.0
HalSystemInfo.halVendorInfo: Netduino Plus (v4.2.0.1) by Secret Labs LLC
HalSystemInfo.oemCode: 34
HalSystemInfo.modelCode: 177
HalSystemInfo.skuCode: 4097
HalSystemInfo.moduleSerialNumber: 00000000000000000000000000000000
HalSystemInfo.systemSerialNumber: 0000000000000000
ClrInfo.clrVersion: 4.2.0.0
ClrInfo.clrVendorInfo: Netduino Plus (v4.2.0.1) by Secret Labs LLC
ClrInfo.targetFrameworkVersion: 4.2.0.0
SolutionReleaseInfo.solutionVersion: 4.2.0.0
SolutionReleaseInfo.solutionVendorInfo: Netduino Plus (v4.2.0.1) by Secret Labs LLC
SoftwareVersion.BuildDate: Sep 19 2012
SoftwareVersion.CompilerVersion: 410894
FloatingPoint: True
SourceLevelDebugging: True
ThreadCreateEx: True
LCD.Width: 0
LCD.Height: 0
LCD.BitsPerPixel: 0
AppDomains: True
ExceptionFilters: True
IncrementalDeployment: True
SoftReboot: True
Profiling: False
ProfilingAllocations: False
ProfilingCalls: False
IsUnknown: False

ahmedfme wrote Mar 11, 2013 at 6:59 AM

and this the code i am using

using (Socket clientSocket = new Socket(AddressFamily.InterNetwork,
                                                    SocketType.Stream,
                                                    ProtocolType.Tcp))
        {
            // Addressing
            IPAddress ipAddress = IPAddress.Parse(dottedServerIPAddress);
            IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, port);
            // Connecting
            ///Debug.Print("Connecting to server " + serverEndPoint + ".");
            //clientSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            //clientSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, false);

            //clientSocket.SendTimeout = 2000;

            clientSocket.Connect(serverEndPoint);
                ///Debug.Print("Connected to server.");
                // Sending
            byte[] messageBytes = Encoding.UTF8.GetBytes(MSG);
            clientSocket.Send(messageBytes);
            clientSocket.Close();

        }// the socket will be closed here

wrote Mar 20, 2013 at 8:26 AM

wrote Jun 14, 2013 at 10:22 PM

AndreMarschalek wrote Jun 14, 2013 at 10:35 PM

no progress within 7 month?

.netmf 4.2 on a ghi electronics fez spider

wrote Jun 14, 2013 at 10:44 PM

AndreMarschalek wrote Jun 15, 2013 at 7:41 AM

ghi electronics use the lwip stack on all devices

the testcode is simple
Socket ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint RemoteHost = new IPEndPoint(IPAddress.Parse("use a not existing ip"), or use a port where no listener behind);
ClientSocket.Connect(RemoteHost); // this never returns

wrote Jun 16, 2013 at 4:05 PM

wrote Jun 18, 2013 at 11:40 AM

pierre_csa wrote Jul 5, 2013 at 8:32 AM

This is issue is apparently solved in Netmf 4.3 (provided that issue 2045 and 2046 are also fixed), but the exception returns the error code 0. When no response is received, the error code 10060 - Connection timed out should be returned.

wrote Oct 22, 2013 at 6:08 AM

wrote Feb 8, 2014 at 12:22 PM

wrote Jul 31, 2014 at 7:17 PM

wrote Aug 21, 2014 at 9:41 PM

wrote Aug 25, 2014 at 12:39 PM

wrote Aug 27, 2014 at 1:13 AM

ppatierno wrote Aug 31, 2014 at 12:34 PM

I'm using Netduino Plus 2 board with latest version of Net MF 4.3 but the issue is still there...the Connect() method hangs and never returns.
Any news ?

Paolo.

wrote Oct 5, 2014 at 6:05 AM

sam_simsim wrote Oct 23, 2014 at 7:39 AM

Hi, I'm using the Spider and have the same problem! Is there any selution ?

AndreMarschalek wrote Oct 24, 2014 at 6:23 PM

start connect in a new thread and stop this thread after a defined timeout

sam_simsim wrote Oct 26, 2014 at 7:54 AM

Hi AndreMarschalek, my code looks like this:

using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Presentation.Shapes;
using Microsoft.SPOT.Touch;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Microsoft.SPOT;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;
using GHI.Premium.Net;

namespace SocketTcpClientSample1
{
public partial class Program
{

    private string IP;
    private Socket clientSocket;
    private const int port = 8080;
    private IPAddress ipAddress;
    private GT.Timer ledBlinkTimer = new GT.Timer(1000);
    private IPEndPoint serverEndPoint;
    private bool con = false;
    // This method is run when the mainboard is powered up or reset.   
    void ProgramStarted()
    {
        ledBlinkTimer.Tick += new GT.Timer.TickEventHandler(ledBlinkTimer_Tick);
        using (clientSocket = new Socket(AddressFamily.InterNetwork,
                                                        SocketType.Stream,
                                                        ProtocolType.Tcp))
        {


            // initializes ethernet
              initethernetConnection();

             ipAddress = IPAddress.Parse(IP);
             serverEndPoint = new IPEndPoint(ipAddress, port);

             ledBlinkTimer.Start();




        }// the socket will be closed here


    }

    private void ledBlinkTimer_Tick(GT.Timer timer)
    {
        // Connecting
        Debug.Print("Connecting to server " + serverEndPoint + ".");

        if(con==false){
        clientSocket.Connect(new IPEndPoint(ipAddress, port));

        Debug.Print("Connected to server.");
        con = true;
        }
        // Sending
        byte[] messageBytes = Encoding.UTF8.GetBytes("Hello World!");

        clientSocket.Send(messageBytes);
    }
      // Just helper to initialize ethernet connection, nothing to do with SocketIO
    void initethernetConnection()
    {
        Debug.Print("connecting to Ethernet ");
        if (ethernet_J11D.Interface.IsOpen)
        {
            Debug.Print("interface was open");
        }
        else
        {
            Debug.Print("interface was not open");
            ethernet_J11D.Interface.Open();
        }

        ethernet_J11D.Interface.CableConnectivityChanged +=
            new EthernetBuiltIn.CableConnectivityChangedEventHandler((s, e) =>
        {
            Debug.Print("Ethernet conn changed!");
            if (e.IsConnected) { Debug.Print("ETHERNET connected!"); }
            else { Debug.Print("Ethernet  disconnected.."); }
        });

        ethernet_J11D.DebugPrintEnabled = true;
        ethernet_J11D.UseDHCP();
        ethernet_J11D.UseThisNetworkInterface();
        Thread.Sleep(3000);
       IP = ethernet_J11D.NetworkSettings.IPAddress;
}
}
}

AndreMarschalek wrote Oct 27, 2014 at 1:21 PM

private ManualResetEvent Connected;
         private Socket ClientSocket;
         private Thread tConnect;
         private Timer TimeOut;

         private void Server_Connect()
         {
             try
             {
                 IPEndPoint RemoteHost = new IPEndPoint(Dns.GetHostEntry(SmtpServer).AddressList[0], SmtpServerPort);
                 tConnect = new Thread(() => Socket_Connect(RemoteHost));
                 TimeOut = new Timer(new TimerCallback(TimeOut_tick), null, 5 * 1000, Timeout.Infinite);
                 tConnect.Start();
                 Connected.WaitOne();

                 if (ClientSocket == null)
                     throw new Exception("Connect failed TimeOut");

                 // further Socket Processing
             }
             catch
             {
                 throw;
             }
         }

         private void Socket_Connect(IPEndPoint RemoteHost)
         {
             ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             ClientSocket.Connect(RemoteHost); // <a href="http://netmf.codeplex.com/workitem/1830" target="_blank">http://netmf.codeplex.com/workitem/1830</a>
             TimeOut.Dispose();
             Connected.Set();
         }

         private void TimeOut_tick(object state)
         {
             TimeOut.Dispose();
             tConnect.Abort();
             ClientSocket = null;
             Connected.Set();
         }

sam_simsim wrote Oct 28, 2014 at 11:10 AM

when I try this code I get this error:

Exception System.Net.Sockets.SocketException - CLR_E_FAIL (4)

#### Message: 
#### Microsoft.SPOT.Net.SocketNative::connect [IP: 0000] ####
#### System.Net.Sockets.Socket::Connect [IP: 001d] ####
#### GadgeteerTCP2.Program+<>c__DisplayClass1::<Server_Connect>b__0 [IP: 000b] ####
#### SocketException ErrorCode = 10054
#### SocketException ErrorCode = 10054
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in Microsoft.SPOT.Net.dll
#### SocketException ErrorCode = 10054
An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in Microsoft.SPOT.Net.dll

AndreMarschalek wrote Oct 28, 2014 at 11:38 AM

Connection reset by peer.
An existing connection was forcibly closed by the remote host. This normally results if the peer application on the remote host is suddenly stopped, the host is rebooted, the host or remote network interface is disabled, or the remote host uses a hard close (see setsockopt for more information on the SO_LINGER option on the remote socket). This error may also result if a connection was broken due to keep-alive activity detecting a failure while one or more operations are in progress. Operations that were in progress fail with WSAENETRESET. Subsequent operations fail with WSAECONNRESET.

sam_simsim wrote Oct 28, 2014 at 8:41 PM

I changed the IP-adress from 127.0.0.1 to 192.168.1.5, and now it's error at "throw"
catch
        {
            throw;   <-----
        }
I get:

Exception System.NullReferenceException - CLR_E_NULL_REFERENCE (1)

#### Message: 
#### GadgeteerTCP2.Program::Server_Connect [IP: 0056] ####
#### GadgeteerTCP2.Program::ProgramStarted [IP: 0005] ####
#### GadgeteerTCP2.Program::Main [IP: 0015] ####
A first chance exception of type 'System.NullReferenceException' occurred in GadgeteerTCP2.exe
A first chance exception of type 'System.NullReferenceException' occurred in GadgeteerTCP2.exe

An unhandled exception of type 'System.NullReferenceException' occurred in GadgeteerTCP2.exe

the code looks like this:



using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Presentation.Shapes;
using Microsoft.SPOT.Touch;
using System.Net.Sockets;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using System.Net;
using System.Text;

namespace GadgeteerTCP2
{
public partial class Program
{
     private byte[] messageBytes;
     private ManualResetEvent Connected;
     private Socket ClientSocket;
     private Thread tConnect;
     private Timer TimeOut;
     private string SmtpServer = "192.168.1.5";
     private int SmtpServerPort=8080;
    // This method is run when the mainboard is powered up or reset.   
    void ProgramStarted()
    {
        Server_Connect();
         messageBytes = Encoding.UTF8.GetBytes("Hello World!");
         ClientSocket.Send(messageBytes);
        byte[] inBuffer = new byte[100];
        int count = ClientSocket.Receive(inBuffer);
        char[] chars = Encoding.UTF8.GetChars(inBuffer);
        string str = new string(chars, 0, count);
        Debug.Print(str); 

    }
    private void Server_Connect()
    {
        try
        {
            IPEndPoint RemoteHost = new IPEndPoint(Dns.GetHostEntry(SmtpServer).AddressList[0], SmtpServerPort);
            tConnect = new Thread(() => Socket_Connect(RemoteHost));
            TimeOut = new Timer(new TimerCallback(TimeOut_tick), null, 5 * 1000, Timeout.Infinite);

            tConnect.Start();
            Connected.WaitOne();


            if (ClientSocket == null)
                throw new Exception("Connect failed TimeOut");

            // further Socket Processing
        }
        catch
        {
            throw;
        }
    }



    private void Socket_Connect(IPEndPoint RemoteHost)
    {
        ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        ClientSocket.Connect(RemoteHost); // <a href="http://netmf.codeplex.com/workitem/1830" target="_blank">http://netmf.codeplex.com/workitem/1830</a>
        TimeOut.Dispose();
        Connected.Set();
    }

    private void TimeOut_tick(object state)
    {
        TimeOut.Dispose();
        tConnect.Abort();
        ClientSocket = null;
        Connected.Set();
    }
}
}

AndreMarschalek wrote Oct 28, 2014 at 10:08 PM

ref your code you posted on Sun at 8:54 AM
what i posted is a code snippet, an extension to your code and not a full replacement of your code to give you an overview how you can use socket.connect in a thread to avoid a forever hanging socket.connect

btw Gadgeteer's ProgramStarted exists to give you the possibility to initialize something for example to attach network event handlers and its important to let that finish to enable the full Gadgeteer dispatcher to work before you work with your network or other stuff but thats out of this topic

sam_simsim wrote Oct 31, 2014 at 4:47 PM

Thank you And Marschalek, I used the code example and it does not charging any more but I still have problem with connection to the server :/. can you please take a look at the code?


using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Presentation.Shapes;
using Microsoft.SPOT.Touch;
using System.Net.Sockets;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using System.Net;
using System.Text;
using Gadgeteer.Modules.GHIElectronics;
using GHI.Premium.Net;

namespace GadgeteerTCP2
{
public partial class Program
{
     private byte[] messageBytes;
     private ManualResetEvent Connected;
     private Socket ClientSocket;
     private Thread tConnect;
     private Timer TimeOut;
     public string SmtpServer = "192.168.1.5";
     private int SmtpServerPort=8080;
    // This method is run when the mainboard is powered up or reset.   
    void ProgramStarted()
    {
        ethernet_J11D.DebugPrintEnabled = true;
        ethernet_J11D.UseDHCP();
        ethernet_J11D.UseThisNetworkInterface();

        ethernet_J11D.NetworkUp += new GTM.Module.NetworkModule.NetworkEventHandler(ethernet_NetworkUp);


    }

    void ethernet_NetworkUp(GTM.Module.NetworkModule sender, GTM.Module.NetworkModule.NetworkState state)
    {
       initethernetConnection();

    }



    void initethernetConnection()
    {
        Debug.Print("connecting to Ethernet ");
        if (ethernet_J11D.Interface.IsOpen)
        {
            Debug.Print("interface was open");
        }
        else
        {
            Debug.Print("interface was not open");
            ethernet_J11D.Interface.Open();
        }

        ethernet_J11D.Interface.CableConnectivityChanged +=
            new EthernetBuiltIn.CableConnectivityChangedEventHandler((s, e) =>
            {
                Debug.Print("Ethernet conn changed!");
                if (e.IsConnected) { Debug.Print("ETHERNET connected!"); }
                else { Debug.Print("Ethernet  disconnected.."); }
            });
        Thread.Sleep(3000);

        var settings = ethernet_J11D.NetworkSettings;

        Debug.Print("------------------------------------------------");
        //Debug.Print("MAC: " + ByteExten.ToHexString(settings.PhysicalAddress, "-"));
        Debug.Print("IP Address:   " + settings.IPAddress);
        Debug.Print("DHCP Enabled: " + settings.IsDhcpEnabled);
        Debug.Print("Subnet Mask:  " + settings.SubnetMask);
        Debug.Print("Gateway:      " + settings.GatewayAddress);
        Debug.Print("------------------------------------------------");


        //SmtpServer = settings.IPAddress;

        Server_Connect();

        messageBytes = Encoding.UTF8.GetBytes("Hello World!");
        ClientSocket.Send(messageBytes);
        byte[] inBuffer = new byte[100];
        int count = ClientSocket.Receive(inBuffer);
        char[] chars = Encoding.UTF8.GetChars(inBuffer);
        string str = new string(chars, 0, count);
        Debug.Print(str); 



    }
    private void Server_Connect()
    {
        try
        {
            IPEndPoint RemoteHost = new IPEndPoint(Dns.GetHostEntry(SmtpServer).AddressList[0], SmtpServerPort);
            tConnect = new Thread(() => Socket_Connect(RemoteHost));
            TimeOut = new Timer(new TimerCallback(TimeOut_tick), null, 5 * 1000, Timeout.Infinite);

            tConnect.Start();
            Connected.WaitOne();


            if (ClientSocket == null)
                throw new Exception("Connect failed TimeOut");

            // further Socket Processing
        }
        catch
        {
            throw;
        }
    }



    private void Socket_Connect(IPEndPoint RemoteHost)
    {
        ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        ClientSocket.Connect(RemoteHost); // <a href="http://netmf.codeplex.com/workitem/1830" target="_blank">http://netmf.codeplex.com/workitem/1830</a>
        TimeOut.Dispose();
       Connected.Set();
    }

    private void TimeOut_tick(object state)
    {
        TimeOut.Dispose();
        tConnect.Abort();
        ClientSocket = null;
        Connected.Set();
    }
}
}

and I get this error:

connecting to Ethernet

interface was open

IP Address: 192.168.1.5
DHCP Enabled: True
Subnet Mask: 255.255.255.0

Gateway: 192.168.1.254

#### Exception System.Net.Sockets.SocketException - CLR_E_FAIL (6) ####
#### Message: 
#### Microsoft.SPOT.Net.SocketNative::connect [IP: 0000] ####
#### System.Net.Sockets.Socket::Connect [IP: 001d] ####
#### GadgeteerTCP2.Program+<>c__DisplayClass3::<Server_Connect>b__2 [IP: 000b] ####
#### SocketException ErrorCode = 10054
#### SocketException ErrorCode = 10054
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in Microsoft.SPOT.Net.dll
#### SocketException ErrorCode = 10054

wrote Feb 17 at 1:39 PM

wrote May 6 at 8:34 PM