changeset 2118:995c45c244ed

Improve WebSocket handling a bit.
author Matti Hamalainen <ccr@tnsp.org>
date Tue, 10 Sep 2019 21:15:25 +0300
parents eb05d61f969c
children 5b0fd5ee79a4
files www/search.js
diffstat 1 files changed, 46 insertions(+), 40 deletions(-) [+]
line wrap: on
line diff
--- a/www/search.js	Tue Sep 10 19:53:21 2019 +0300
+++ b/www/search.js	Tue Sep 10 21:15:25 2019 +0300
@@ -151,21 +151,45 @@
 }
 
 
+function mapSetupWebSocket()
+{
+  if ("WebSocket" in window)
+  {
+    var tmpWS = new WebSocket(mapServer);
+    if (!tmpWS)
+    {
+      mapResult("WebSocket error: Could not create WebSocket.");
+      return null;
+    }
+
+    tmpWS.onerror = function(mev)
+    {
+      mapResult("WebSocket error occured.");
+      console.error("WebSocket error occured: ", mev);
+    };
+
+    return tmpWS;
+  }
+  else
+  {
+    mapResult("Your browser does not support WebSockets.");
+    return null;
+  }
+}
+
+
 function mapGetData()
 {
-  var tmpWS = new WebSocket(mapServer);
-  if (!tmpWS)
-  {
-    mapLog("Could not create WebSocket connection?");
+  var dataWS = mapSetupWebSocket();
+  if (!dataWS)
     return;
-  }
 
-  tmpWS.onopen = function()
+  dataWS.onopen = function()
   {
-    tmpWS.send("GETMAPS");
+    dataWS.send("GETMAPS");
   };
 
-  tmpWS.onmessage = function(evt)
+  dataWS.onmessage = function(evt)
   {
     if (evt.data.substr(0, 6) == "ERROR:")
     {
@@ -206,12 +230,7 @@
         mapResult("ERROR: "+ results);
     }
 
-    tmpWS.close();
-  };
-
-  tmpWS.onerror = function()
-  {
-    mapResult("WebSocket error occured.");
+    dataWS.close();
   };
 }
 
@@ -280,7 +299,7 @@
   }
 
   // Open a WebSocket connection ..
-  mapWS = new WebSocket(mapServer);
+  mapWS = mapSetupWebSocket();
   if (!mapWS)
     return;
 
@@ -292,6 +311,12 @@
     mapWS.send("MAPSEARCH:"+ -1 +":"+ searchList.join(":") +"\n" + fieldPattern.value);
   };
 
+  mapWS.onclose = function()
+  {
+    mapWS = null;
+    btnMapSearch.disabled = false;
+  };
+
   // Register events
   mapWS.onmessage = function(evt)
   {
@@ -336,17 +361,6 @@
 
     mapWS.close();
   };
-
-  mapWS.onclose = function()
-  {
-    mapWS = null;
-    btnMapSearch.disabled = false;
-  };
-
-  mapWS.onerror = function()
-  {
-    mapResult("WebSocket error occured.");
-  };
 }
 
 
@@ -381,12 +395,9 @@
     return;
 
   // Open a WebSocket connection ..
-  locWS = new WebSocket(mapServer);
+  locWS = mapSetupWebSocket();
   if (!locWS)
-  {
-    mapResult("Could not create WebSocket connection?");
     return;
-  }
 
   locWS.onopen = function()
   {
@@ -394,6 +405,11 @@
     locWS.send(nearby ? "LOCNEAR:"+ tmp +":" : "LOCSEARCH:*"+ tmp +"*");
   };
 
+  locWS.onclose = function()
+  {
+    locWS = null;
+  };
+
   // Register events
   locWS.onmessage = function(evt)
   {
@@ -446,16 +462,6 @@
 
     locWS.close();
   };
-
-  locWS.onclose = function()
-  {
-    locWS = null;
-  };
-
-  locWS.onerror = function()
-  {
-    mapResult("WebSocket error occured.");
-  };
 }