Blame view

code/server.go 1.16 KB
1f34ee88   Lars Tiede   after presentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
  package main
  
  import (
  	"fmt"
  	"net/http"
  	"strconv"
  	"time"
  
  	"github.com/gorilla/mux"
  	"github.com/gorilla/websocket"
  )
  
  func main() {
  	// set up and run http server
  	routes := mux.NewRouter()
  	routes.HandleFunc("/", serveHTMLFileHandler)
  	routes.HandleFunc("/ws_demo", websocketHandler)
  	http.ListenAndServe("localhost:4040", routes)
  }
  
  func serveHTMLFileHandler(w http.ResponseWriter, r *http.Request) {
  	http.ServeFile(w, r, "./client.html")
  }
  
  func websocketHandler(w http.ResponseWriter, r *http.Request) {
  	// "upgrade" http connection to websocket connection
  	upgrader := websocket.Upgrader{}
  	conn, err := upgrader.Upgrade(w, r, nil)
  	if err != nil {
  		fmt.Println(err)
  		return
  	}
  
  	// read number from client
  	_, textFromClient, err := conn.ReadMessage()
  	if err != nil {
  		return
  	}
  	number, _ := strconv.ParseInt(string(textFromClient), 10, 64)
  
  	// until connection is closed by client, increment number and send
  	// it to the client, once every second
  	for {
  		number += 1
  		time.Sleep(1 * time.Second)
  		err = conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("%d", number)))
  		if err != nil { // this happens when connection has been closed
  			return
  		}
  	}
  }