Selaa lähdekoodia

Websockets for auto-reloading of the image

Gildas Chabot 8 vuotta sitten
vanhempi
commit
c741deca92
3 muutettua tiedostoa jossa 47 lisäystä ja 1 poistoa
  1. 1 1
      buildAndRun.sh
  2. 35 0
      index.html
  3. 11 0
      main.go

+ 1 - 1
buildAndRun.sh

@@ -18,7 +18,7 @@ mv -f `find $pluginSrc -name '*.so'` plugins.available/
18 18
 
19 19
 # Compile main app
20 20
 
21
-docker run --rm -v "$PWD":/usr/src/myapp -w /usr/src/myapp golang:1.8 go build
21
+docker run --rm -v "$PWD":/usr/src/myapp -w /usr/src/myapp golang:1.8 /bin/bash -c "go get golang.org/x/net/websocket && go build"
22 22
 
23 23
 # Run it
24 24
 

+ 35 - 0
index.html

@@ -0,0 +1,35 @@
1
+<!DOCTYPE HTML>
2
+<html>
3
+    <head>
4
+	    <title>GildasCh</title>
5
+	    <meta charset='utf-8' />
6
+        <style>
7
+         body {
8
+             background-color:#263238;
9
+         }
10
+         img {
11
+             position: absolute;
12
+             top: 50%;
13
+             left: 50%;
14
+             width: 425px;
15
+             height: 224px;
16
+             margin-left: -212px; /* Half the width */
17
+             margin-top: -112px; /* Half the height */
18
+         }
19
+        </style>
20
+    </head>
21
+    <body>
22
+
23
+        <img id='image' style='-webkit-user-select: none' src='http://localhost:8080/a.jpg' />
24
+
25
+        <script>
26
+         var connection = new WebSocket('ws://localhost:8080/ws', []);
27
+         var counter = 0;
28
+         connection.onmessage = function (e) {
29
+           document.getElementById('image').src='http://localhost:8080/a.jpg?'+counter;
30
+           console.log('Server: ' + e.data);
31
+           counter++;
32
+         };
33
+        </script>
34
+    </body>
35
+</html>

+ 11 - 0
main.go

@@ -10,6 +10,9 @@ import (
10 10
 	"os"
11 11
 	"path"
12 12
 	"plugin"
13
+	"time"
14
+
15
+	"golang.org/x/net/websocket"
13 16
 )
14 17
 
15 18
 type Transformer struct {
@@ -95,11 +98,19 @@ func handler(w http.ResponseWriter, r *http.Request) {
95 98
 	jpeg.Encode(w, i, nil)
96 99
 }
97 100
 
101
+func wsHandler(ws *websocket.Conn) {
102
+	for true {
103
+		fmt.Fprintf(ws, "echp")
104
+		time.Sleep(200 * time.Millisecond)
105
+	}
106
+}
107
+
98 108
 var pluginDir string
99 109
 
100 110
 func main() {
101 111
 	pluginDir = os.Args[1]
102 112
 
103 113
 	http.HandleFunc("/a.jpg", handler)
114
+	http.Handle("/ws", websocket.Handler(wsHandler))
104 115
 	http.ListenAndServe(":8080", nil)
105 116
 }