allow multiple websocket connections
This commit is contained in:
parent
af435cf958
commit
8ef8de0943
|
@ -0,0 +1,5 @@
|
||||||
|
module go-buzz
|
||||||
|
|
||||||
|
go 1.23.2
|
||||||
|
|
||||||
|
require github.com/gorilla/websocket v1.5.3
|
|
@ -0,0 +1,2 @@
|
||||||
|
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||||
|
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
|
@ -0,0 +1,47 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
"net/http"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/gorilla/websocket"
|
||||||
|
)
|
||||||
|
|
||||||
|
type webSocketHandler struct {
|
||||||
|
upgrader websocket.Upgrader
|
||||||
|
}
|
||||||
|
|
||||||
|
// GLOBALS
|
||||||
|
var connections int = 0
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
|
||||||
|
func (wsh webSocketHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||||
|
//upgrade http connection to websocket
|
||||||
|
connection, err := wsh.upgrader.Upgrade(w, r, nil)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("Error while upgrading connection to websocket: %s", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
connections++
|
||||||
|
log.Printf("New websocket connection. There are now %v\n", connections)
|
||||||
|
wg.Add(1)
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
defer connection.Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
webSocketHandler := webSocketHandler{
|
||||||
|
upgrader: websocket.Upgrader{},
|
||||||
|
}
|
||||||
|
var port string = "8080"
|
||||||
|
http.Handle("/", webSocketHandler)
|
||||||
|
wg.Add(1)
|
||||||
|
log.Printf("listening on port %s...\n", port)
|
||||||
|
log.Fatal(http.ListenAndServe("localhost:8080", nil))
|
||||||
|
wg.Wait()
|
||||||
|
}
|
Loading…
Reference in New Issue