diff rlgterm.js @ 100:3dbfdaf62623

RLG-Web: begin converting to WebSockets. Use WebSockets for watching, if the browser supports it. Functionality is not complete yet.
author John "Elwin" Edwards <elwin@sdf.org>
date Thu, 12 Jul 2012 22:16:15 -0700
parents 8a748eac7c11
children e59d68082664
line wrap: on
line diff
--- a/rlgterm.js	Thu Jul 12 07:58:23 2012 -0700
+++ b/rlgterm.js	Thu Jul 12 22:16:15 2012 -0700
@@ -82,7 +82,9 @@
   lname: null,
   lcred: null,
   /* Whether the game is being played or just watched. */
-  playing: false
+  playing: false,
+  /* WebSocket for communication */
+  sock: null
 };
 
 /* The interval ID for checking the status of current games. */
@@ -655,6 +657,10 @@
 function startwatching(gamenumber) {
   if (session.id != null)
     return;
+  if (WebSocket) {
+    wsWatch(gamenumber);
+    return;
+  }
   var wmsg = {"n": Number(gamenumber)};
   var req = new XMLHttpRequest();
   req.onerror = errHandler;
@@ -692,6 +698,27 @@
   return watcher;
 }
 
+function wsWatch(gamenumber) {
+  var sockurl = "ws://localhost:8080/watch/" + String(gamenumber);
+  var ws = new WebSocket(sockurl);
+  ws.onopen = function (event) {
+    session.id = true;
+    session.sock = ws;
+    message("You are now watching game #" + gamenumber + ".");
+    setmode("watch");
+  };
+  ws.onmessage = function (event) {
+    var msgObject = JSON.parse(event.data);
+    if (msgObject.t == 'd') {
+      writeData(msgObject.d);
+    }
+  };
+  ws.onclose = function (event) {
+    session.sock = null;
+    gameover();
+  };
+}
+
 function formreg(ev) {
   ev.preventDefault();
   if (session.id != null)
@@ -775,6 +802,10 @@
 function stop() {
   if (!session.id)
     return;
+  if (session.sock) {
+    session.sock.close();
+    return;
+  }
   var req = new XMLHttpRequest();
   req.onerror = errHandler;
   req.onreadystatechange = function () {