Pushbutton Web Examples


Long-Poll Server in Go


package main

import (
  "http"
  "log"
  "io"
  "io/ioutil"
)

var messages chan string = make(chan string, 100)

func PushHandler(w http.ResponseWriter, req *http.Request) {

  body, err := ioutil.ReadAll(req.Body)

  if err != nil {
w.WriteHeader(400)
  }
  messages <- string(body)
}


func PollResponse(w http.ResponseWriter, req *http.Request) {
  io.WriteString(w, <-messages)  /**** Blocks if no message! ****/
}

func main() {
  http.Handle("/", http.FileServer(http.Dir("./")))
  http.HandleFunc("/poll", PollResponse)
  http.HandleFunc("/push", PushHandler)
  err := http.ListenAndServe(":12345", nil)
  if err != nil {
    log.Fatal("ListenAndServe: ", err.String())
  }
}


Long-Poll in JavaScript


function longpoll(url, callback) {

  var req = new XMLHttpRequest (); 
  req.open ('GET', url, true); 

  req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) { 
  if (req.status == 200) {
  callback(req.responseText);
  longpoll(url, callback);
  } else {
  alert ("long-poll connection lost");
  }
  }
  };

  req.send(null);
}

Also, see attachments below.

ċ
chatdemo.tar.gz
(1k)
Ryanne Dolan,
Nov 30, 2010, 8:22 AM
ċ
longpolldemo.tar.gz
(1k)
Ryanne Dolan,
Nov 30, 2010, 8:22 AM
Comments