Skip to content

Instantly share code, notes, and snippets.

@okaq
Created August 13, 2014 12:37
Show Gist options
  • Save okaq/f1bb292c703b40e93fb0 to your computer and use it in GitHub Desktop.
Save okaq/f1bb292c703b40e93fb0 to your computer and use it in GitHub Desktop.
WebSocket Texture Sythesis Test
/*
* Golang okaq yamo zendo web server
* Websocket texture synth
* AQ <[email protected]>
* 2014-06-18
*/
package main
import (
"log"
"math/rand"
"net/http"
"time"
"github.com/gorilla/websocket"
)
const (
PORT = ":8000"
ZENDO = "/home/ahmad/Documents/gira/yamo/src/zendo/zendo.html"
)
var (
upg = websocket.Upgrader{
ReadBufferSize: 64,
WriteBufferSize: 64,
}
rng = rand.New(rand.NewSource(time.Now().UnixNano()))
)
func RB() int {
return rng.Intn(256)
}
func RA() byte {
return byte(97 + rng.Intn(26))
}
func RS(n int) []byte {
b := make([]byte, n)
for i := 0; i < n; i++ {
b[i] = RA()
}
return b
}
func ZendoHandler(w http.ResponseWriter, r *http.Request) {
// log.Println(r)
http.ServeFile(w, r, ZENDO)
}
func WsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "GET Method Only!", 405)
return
}
conn, err := upg.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
// log.Println(conn, upg)
mt, p, err := conn.ReadMessage()
if err != nil {
log.Println(err)
}
log.Println(mt, string(p))
c := time.Tick(1 * time.Second)
for i := 0; i < 16; i++ {
now := <-c
log.Println(i, now)
// rgba := []byte("rgba")
// rgba := []byte{114,103,98,97}
rgba := RS(16)
// sends as DOM Blob
conn.WriteMessage(websocket.BinaryMessage, rgba)
// sends as DOM String
// conn.WriteMessage(webSocket.TextMessage, rgba)
}
// close(c)
}
func main() {
http.HandleFunc("/", ZendoHandler)
http.HandleFunc("/ws", WsHandler)
log.Fatal(http.ListenAndServe(PORT, nil))
}
<!DOCTYPE html>
<html lang="en">
<head id="zeta">
<title>okaq</title>
<script type="text/javascript">
// ok
console.log("ok zendo!");
var ws = new WebSocket("ws://localhost:8000/ws");
console.log(ws);
ws.onopen = function(e) {
console.log(e);
ws.send("rgba: 128,128,128,1.0");
}
ws.onclose = function(e) {
console.log(e);
}
ws.onmessage = function(e) {
console.log(e.data);
var r = new FileReader();
r.addEventListener("loadend", function() {
console.log(r.result);
var b = new Uint8Array(r.result);
console.log(b);
var t = "";
for (var i = 0; i < b.length; i++) {
t = t + String.fromCharCode(b[i]);
}
console.log("rgba: " + t);
});
r.readAsArrayBuffer(e.data);
}
</script>
</head>
<body id="alpha">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment