]> git.mxchange.org Git - simgear.git/blobdiff - simgear/io/sg_netChannel.cxx
Asynchronous host lookups+caching, attempt #2
[simgear.git] / simgear / io / sg_netChannel.cxx
index c3644b6c275d5d915d5844da112802f4efc6df6d..86839e71a707384661f9a5555cdd1f7d38e3e0d2 100644 (file)
@@ -38,6 +38,7 @@
 
 #include <simgear/debug/logstream.hxx>
 
+
 namespace simgear  {
 
 static NetChannel* channels = 0 ;
@@ -46,6 +47,7 @@ NetChannel::NetChannel ()
 {
   closed = true ;
   connected = false ;
+  resolving_host  = false;
   accepting = false ;
   write_blocked = false ;
   should_delete = false ;
@@ -83,7 +85,6 @@ NetChannel::setHandle (int handle, bool is_connected)
   close () ;
   Socket::setHandle ( handle ) ;
   connected = is_connected ;
-  //if ( connected ) this->handleConnect();
   closed = false ;
 }
 
@@ -107,21 +108,12 @@ NetChannel::listen ( int backlog )
 }
 
 int
-NetChannel::connect ( const char* host, int port )
+NetChannel::connect ( const char* h, int p )
 {
-  int result = Socket::connect ( host, port ) ;
-  if (result == 0) {
-    connected = true ;
-    //this->handleConnect();
-    return 0;
-  } else if (isNonBlockingError ()) {
-    return 0;
-  } else {
-    // some other error condition
-    this->handleError (result);
-    close();
-    return -1;
-  }
+  host = h;
+  port = p;
+  resolving_host = true;
+  return handleResolve();
 }
 
 int
@@ -189,12 +181,10 @@ NetChannel::handleReadEvent (void)
   if (accepting) {
     if (!connected) {
       connected = true ;
-      //this->handleConnect();
     }
     this->handleAccept();
   } else if (!connected) {
     connected = true ;
-    //this->handleConnect();
     this->handleRead();
   } else {
     this->handleRead();
@@ -206,12 +196,35 @@ NetChannel::handleWriteEvent (void)
 {
   if (!connected) {
     connected = true ;
-    //this->handleConnect();
   }
   write_blocked = false ;
   this->handleWrite();
 }
 
+int
+NetChannel::handleResolve()
+{
+    IPAddress addr;
+    if (!IPAddress::lookupNonblocking(host.c_str(), addr)) {
+        return 0; // not looked up yet, wait longer
+    }
+    
+    resolving_host = false;
+    addr.setPort(port);
+    int result = Socket::connect ( &addr ) ;
+    if (result == 0) {
+        connected = true ;
+        return 0;
+    } else if (isNonBlockingError ()) {
+        return 0;
+    } else {
+        // some other error condition
+        handleError (result);
+        close();
+        return -1;
+    }
+}
+
 bool
 NetChannel::poll (unsigned int timeout)
 {
@@ -236,6 +249,12 @@ NetChannel::poll (unsigned int timeout)
     }
     else if ( ! ch -> closed )
     {
+      if (ch -> resolving_host )
+      {
+          ch -> handleResolve();
+          continue;
+      }
+      
       nopen++ ;
       if (ch -> readable()) {
         assert(nreads<MAX_SOCKETS);