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;
}
}
Isn’t this going to still have the same problem at the “connect” line. Won’t the “Connect” still be blocking and thus it will just sit there and wait? Or am I missing something?
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
[b] clientSocket.Connect(serverEndPoint);[/b]
Debug.Print("Connected to remote server");
How about calling socket Connect in a separate thread. In your main thread you can set a timer to timeout after say 3 seconds. At timer timeout, you could check to see if your socket is connected. If not, abort the thread.
Thanks Jasdev, that is probably how I will have to do it. Hate to do it that way was trying to keep the threads to a minimum and keep things simple. But I tossed and turned and could not think of anything better.
Architect, thanks for the pointer to the FTP code! It did give me some good ideas on how to communicate back and forth.