server.go 1.16 KB
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
		}
	}
}