handle errors a bit more gracefully in NetworkTCP
authorterom
Sat, 06 Dec 2008 20:56:24 +0000
changeset 227 39cd6861e43e
parent 226 381487d07d17
child 228 dbc1bb7a98b5
handle errors a bit more gracefully in NetworkTCP
src/Error.cc
src/Error.hh
src/Network/TCP.cc
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/Error.cc	Sat Dec 06 20:56:24 2008 +0000
@@ -0,0 +1,7 @@
+
+#include "Error.hh"
+
+std::ostream& operator<< (std::ostream &s, Error &e) {
+    return s << e.what();
+}
+
--- a/src/Error.hh	Sat Dec 06 19:49:58 2008 +0000
+++ b/src/Error.hh	Sat Dec 06 20:56:24 2008 +0000
@@ -1,6 +1,8 @@
 #ifndef ERROR_HH
 #define ERROR_HH
 
+#include "Logger.hh"
+
 #include <stdexcept>
 #include <string>
 
@@ -16,4 +18,6 @@
         }
 };
 
+std::ostream& operator<< (std::ostream &s, Error &e);
+
 #endif /* ERROR_HH */
--- a/src/Network/TCP.cc	Sat Dec 06 19:49:58 2008 +0000
+++ b/src/Network/TCP.cc	Sat Dec 06 20:56:24 2008 +0000
@@ -19,22 +19,42 @@
     uint32_t length;
     char *buf_ptr;
     
-    // let the in stream read length-prefixed packets and pass them on to handle_packet
-    while (in.peek_data<uint32_t>(length, buf_ptr)) {
-        // allocate the NetworkPacketBuffer with the given buf_ptr/length
-        NetworkPacketBuffer packet(buf_ptr, length, length);
-        
-        // pass the packet on
-        _sig_packet(packet);
+    try { 
+        // let the in stream read length-prefixed packets and pass them on to handle_packet
+        do {
+            // not enough data -> return and wait 
+            if (in.peek_data<uint32_t>(length, buf_ptr) == false)
+                break;
 
-        // flush it
-        in.flush_data<uint32_t>();
+            // allocate the NetworkPacketBuffer with the given buf_ptr/length
+            NetworkPacketBuffer packet(buf_ptr, length, length);
+            
+            // pass the packet on
+            _sig_packet(packet);
+
+            // flush it
+            in.flush_data<uint32_t>();
+        } while (true);
+
+    } catch (NetworkSocketError &e) {
+        // log and disconnect
+        Engine::log(ERROR, "tcp.on_read") << "socket error: " << e.what();
+
+        _sig_disconnect();
     }
 }
 
 void NetworkTCPTransport::on_write (void) {
-    // just flush the output buffer
-    out.flush_write();
+    try {
+        // just flush the output buffer
+        out.flush_write();
+
+    } catch (NetworkSocketError &e) {
+        // log and disconnect
+        Engine::log(ERROR, "tcp.on_write") << "socket error: " << e.what();
+
+        _sig_disconnect();
+    }
 }
 
 void NetworkTCPTransport::on_disconnected (void) {
@@ -52,7 +72,7 @@
         // just write to the output buffer
         out.write_prefix((char *) packet.get_buf(), prefix);
 
-    } catch (Error &e) {
+    } catch (NetworkSocketError &e) {
         const char *err = e.what();
 
         Engine::log(ERROR, "tcp.write_packet") << err;