diff rlgterm.js @ 108:86a458080e80

RLG-Web client: add playing through WebSockets. Add client-side support for WebSocket play.
author John "Elwin" Edwards <elwin@sdf.org>
date Sun, 15 Jul 2012 18:18:53 -0700
parents dc1414faee19
children 67b393f10c2b
line wrap: on
line diff
--- a/rlgterm.js	Sun Jul 15 09:04:39 2012 -0700
+++ b/rlgterm.js	Sun Jul 15 18:18:53 2012 -0700
@@ -318,12 +318,17 @@
     return;
   }
   ev.preventDefault();
-  var datareq = new XMLHttpRequest();
-  var msgDict = {"id": session.id, "t": "d", "n": nsend++, "d": code};
-  datareq.onerror = errHandler;
-  datareq.onreadystatechange = postResponseHandler;
-  datareq.open('POST', '/feed', true);
-  datareq.send(JSON.stringify(msgDict));
+  if (session.sock) {
+    session.sock.send(JSON.stringify({"t": "d", "d": code}));
+  }
+  else {
+    var datareq = new XMLHttpRequest();
+    var msgDict = {"id": session.id, "t": "d", "n": nsend++, "d": code};
+    datareq.onerror = errHandler;
+    datareq.onreadystatechange = postResponseHandler;
+    datareq.open('POST', '/feed', true);
+    datareq.send(JSON.stringify(msgDict));
+  }
   return;
 }
 
@@ -376,12 +381,17 @@
   }
   else
     return;
-  var datareq = new XMLHttpRequest();
-  var msgDict = {"id": session.id, "t": "d", "n": nsend++, "d": keystr};
-  datareq.onerror = errHandler;
-  datareq.onreadystatechange = postResponseHandler;
-  datareq.open('POST', '/feed', true);
-  datareq.send(JSON.stringify(msgDict));
+  if (session.sock) {
+    session.sock.send(JSON.stringify({"t": "d", "d": keystr}));
+  }
+  else {
+    var datareq = new XMLHttpRequest();
+    var msgDict = {"id": session.id, "t": "d", "n": nsend++, "d": keystr};
+    datareq.onerror = errHandler;
+    datareq.onreadystatechange = postResponseHandler;
+    datareq.open('POST', '/feed', true);
+    datareq.send(JSON.stringify(msgDict));
+  }
   return;
 }
 
@@ -652,6 +662,10 @@
 function startgame(game) {
   if (session.id != null || !session.lcred)
     return;
+  if (WebSocket) {
+    wsStart(game);
+    return;
+  }
   var smsg = {};
   smsg["key"] = session.lcred;
   smsg["game"] = game.uname;
@@ -695,6 +709,32 @@
   return;
 }
 
+function wsStart(game) {
+  var sockurl = "ws://" + window.location.host + "/play/" + game.uname;
+  sockurl += "?key=" + session.lcred + "&w=80&h=24";
+  ws = new WebSocket(sockurl);
+  ws.onopen = function (event) {
+    session.id = true;
+    session.playing = true;
+    session.sock = ws;
+    setmode("play");
+  };
+  ws.onmessage = function (event) {
+    var msgObject = JSON.parse(event.data);
+    if (msgObject.t == 's') {
+      termemu.resize(msgObject.h, msgObject.w);
+      message("You are now playing " + msgObject.g + ".");
+    }
+    else if (msgObject.t == 'd') {
+      writeData(msgObject.d);
+    }
+  };
+  ws.onclose = function (event) {
+    session.sock = null;
+    gameover();
+  };
+}
+
 function startwatching(gamenumber) {
   if (session.id != null)
     return;