Commits

desmaj  committed 853fa29

implemented an SSE streaming transport; made streaming actually stream

  • Participants
  • Parent commits f413d88

Comments (0)

Files changed (2)

File src/aquchinchay/csp/server.go

 			batch := newPacketBatch()
 			batch.addPacket(packet)
 			packetJSON := batch.toJSON()
-			fmt.Fprintln(w, packetJSON)
+			fmt.Println(session.prepareBatch(packetJSON))
+			w.Write([]byte(session.prepareBatch(packetJSON)))
+			w.(http.Flusher).Flush()
+			fmt.Println("comet streamed data: " + data)
 			fmt.Println("comet streamed packet")
 		case <- timeout:
 		}

File src/aquchinchay/static/client.js

 	self.url = url;
 	self.readyState = READYSTATE_OPENING;
 	
-	self._transport = new JSONPTransport(self, 30);
+	self._transport = new SSEStreamingTransport(self, 30);
 	self._transport.onread = self._onTransportRead;	
 	self._transport.handshake(function (responseText) {
 	    self.sessionKey = JSON.parse(responseText).session;
 				 setTimeout(self._comet, 0);
 			     });
     }
+}
+    
+var SSEStreamingTransport = function (session, duration) {
+    var self = this;
+    self.duration = duration;
+    
+    self._session = session;
+    
+    self._doRequest = function (endpoint, data, cb) {
+	var cbName = '___xxx_cb_'
+	data["rp"] = cbName + "('";
+	data["rs"] = "')";
+	var url = self._session.url + "/" + endpoint + "?" + $.param(data);
+	
+	var scriptTagID = cbName + 'tag';
+	window[cbName] = function (responseText) {
+	    cb(responseText);
+	    delete window[cbName];
+	    var script = document.getElementById(scriptTagID);
+	    document.body.removeChild(script);
+	}
+	var scriptTag = document.createElement('script');
+	scriptTag.id = scriptTagID;
+	scriptTag.type = "text/javascript";
+	scriptTag.src = url;
+	document.body.appendChild(scriptTag);
+    }
+    
+    self._doCometRequest = function (endpoint, data, cb) {
+	data["bp"] = "data: ";
+	data["bs"] = "\n\n";
+	data["sse"] = "1";	
+	data["is"] = "1";	
+	var url = self._session.url + "/" + endpoint + "?" + $.param(data);
+	var source = new window.EventSource(url);
+	source.addEventListener("message", function (event) {
+	    console.log(event.data);
+	    cb(event.data);
+	});
+    }
+    
+    self.handshake = function (success_cb) {
+	self._doRequest('handshake', {d: {},
+				      du: self.duration,
+				      ct: encodeURI('text/event-stream')
+				     },
+			function (data) {
+			    success_cb(data);
+			    self._comet();
+			});
+    }
+    
+    self.send = function (message, success_cb) {
+	self._doRequest('send', {s: self._session.sessionKey,
+				 d: message},
+			function (data) {
+			    success_cb(data);
+			});
+    }
+    
+    self._comet = function () {
+	var query = {s: self._session.sessionKey,
+		     a: self._session._lastPacketReceived
+		    };
+	self._doCometRequest('comet', query,
+			     function (data) {
+				 self.onread(data)
+			     });
+    }
+    
     
 }