On my G120, I’m trying to connect to a TCP Server. The code below works great if the server is up and running. But I want don’t want to assume that the server is running and handle the inability to connect to the server gracefully. My first thought was to try and use a “non-blocking” connection attempt, but that does not seem to be supported. All I want to do right now is try to connect, if I can great, else try again later.
One other piece of information, the code right now just sits on the “connect” line, even IF I start the server. The code only works if the server is running before the G120 starts running.
public static void Main()
{
WifiSetup();
while (!connectToServer()) { Debug.Print("trying to connect"); Thread.Sleep(1000); }
while (true)
{
Debug.Print("Phone Home");
if (!phoneHome())
{
break;
}
Thread.Sleep(4000);
} // Main Control Loop
} // End Main
private static bool connectToServer()
{
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipe = new IPEndPoint(srvrIP, 2055);
Debug.Print("Waiting For Server");
try
{
// *** This code causes an exception, but I don't think it is what I want anyway.
//client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Linger, new byte[] { 0, 0, 0, 0 });
// ****
client.Connect(ipe);
Debug.Print("Sever Found");
return true;
}
catch
{
return false;
}
}