From 69bf77d799dfad51d6343609fe4aa956ecbd4d8a Mon Sep 17 00:00:00 2001 From: Markus Stoll Date: Tue, 15 Jul 2014 20:58:20 +0200 Subject: [PATCH] Catch SocketException when receiving messages - this can get thrown even if "socket.Available > 0" is true. Treat like timeout by disconnection and reconnecting the notication server --- SparkleLib/SparkleListenerTcp.cs | 56 +++++++++++++++++++------------- 1 file changed, 34 insertions(+), 22 deletions(-) diff --git a/SparkleLib/SparkleListenerTcp.cs b/SparkleLib/SparkleListenerTcp.cs index 5ed07edb..8d6858c7 100755 --- a/SparkleLib/SparkleListenerTcp.cs +++ b/SparkleLib/SparkleListenerTcp.cs @@ -142,15 +142,7 @@ namespace SparkleLib { // The ping failed: disconnect completely } catch (SocketException e) { - this.is_connected = false; - this.is_connecting = false; - - if (this.socket != null) { - this.socket.Close (); - this.socket = null; - } - - OnDisconnected (reason, "Ping timeout: " + e.Message); + Disconnect(reason, "Ping timeout: " + e.Message); return; } @@ -162,23 +154,29 @@ namespace SparkleLib { return; } - if (this.socket.Available > 0) - bytes_read = this.socket.Receive (bytes); + try { + if (this.socket.Available > 0) + bytes_read = this.socket.Receive (bytes); - // Parse the received message - if (bytes_read > 0) { - string received = Encoding.UTF8.GetString (bytes); - string line = received.Substring (0, received.IndexOf ("\n")); + // Parse the received message + if (bytes_read > 0) { + string received = Encoding.UTF8.GetString (bytes); + string line = received.Substring (0, received.IndexOf ("\n")); - if (!line.Contains ("!")) - continue; + if (!line.Contains ("!")) + continue; - string folder_identifier = line.Substring (0, line.IndexOf ("!")); - string message = CleanMessage (line.Substring (line.IndexOf ("!") + 1)); + string folder_identifier = line.Substring (0, line.IndexOf ("!")); + string message = CleanMessage (line.Substring (line.IndexOf ("!") + 1)); - // We have a message! - if (!folder_identifier.Equals ("debug") && !String.IsNullOrEmpty (message)) - OnAnnouncement (new SparkleAnnouncement (folder_identifier, message)); + // We have a message! + if (!folder_identifier.Equals ("debug") && !string.IsNullOrEmpty (message)) + OnAnnouncement (new SparkleAnnouncement (folder_identifier, message)); + } + + } catch (SocketException e) { + Disconnect (DisconnectReason.TimeOut, "Timeout during receiving: " + e.Message); + return; } } }); @@ -187,6 +185,20 @@ namespace SparkleLib { } + private void Disconnect (DisconnectReason reason, string message) + { + this.is_connected = false; + this.is_connecting = false; + + if (this.socket != null) { + this.socket.Close (); + this.socket = null; + } + + OnDisconnected (reason, message); + } + + protected override void AlsoListenToInternal (string folder_identifier) { string to_send = "subscribe " + folder_identifier + "\n";